What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue.

I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav bar. Using text-align:center is causing the button (which only appears on small screens) to overlap the nav bar. How can I address this? Thanks in advance!

Here is the code I have so far:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>TVG</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <style>

  ul.topnav {
    list-style-type: none;
    margin: 0 auto;
    margin-left: 600px;
    padding: 0;
    overflow: hidden;
}

ul.topnav li {float: left;}

ul.topnav li a {
    display: inline-block;
    color: grey;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    transition: 0.3s;
    font-size: 17px;
}

ul.topnav li a:hover {background-color: #555;}

ul.topnav li.icon {display: none;}

@media screen and (max-width:680px) {
    ul.topnav {
        margin: 0 auto;
    }
    ul.topnav li:not(:first-child) {display: none;}
    ul.topnav li.icon {
        float: right;
        display: inline-block;
    }
}

@media screen and (max-width:680px) {
    ul.topnav.responsive {position: relative;}
    ul.topnav.responsive li.icon {
        position: absolute;
        right: 0;
        top: 0;
    }
    ul.topnav.responsive li {
        float: none;
        display: inline;
    }
    ul.topnav.responsive li a {
        display: block;
        text-align: left;
    }
}

#logodiv {
    float:left;
    padding-top:16px;
    padding-left:45px;
    padding-right:7px;
    padding-bottom:3px;
    margin-left:100px;
}

.break{
    clear:both;
    padding-top:10px;
    padding-left:7px;
}   
  </style>
  <body>

    <div id="logodiv">
        <img src="images/bbclogo.png" />
    </div>

    <ul class="topnav mainMenu" id="myTopnav">
        <li><a href="#home">Home</a></li>
        <li><a href="#news">About</a></li>
        <li><a href="#contact">Menu</a></li>
        <li><a href="#about">Contact</a></li>
         <li class="icon">
            <a href="javascript:void(0);" onclick="myFunction()">&#9776;</a>
        </li>
    </ul>

    <div class="break"> </div>

<script>

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}

</script>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

https://jsfiddle.net/85Lc1j6t/#&togetherjs=4Gy02O4Krl

Answer №1

To center a div, apply display: inline-block and margin: 0 auto to the targeted element.

Answer №2

If you're looking to create a responsive navbar, Bootstrap's default navbar is a great option. You can customize it to fit your needs: http://getbootstrap.com/components/#navbar

.navbar-nav {
  width: 100%;
  text-align: center;
}
.navbar-nav > li {
  float: none;
  display: inline-block;
}

For an example of how this setup looks in action, check out this JSFiddle demo: https://jsfiddle.net/7d9fqpsz/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating objects in separate JavaScript files and including them in the main file, along with their

Following the creation of a config.js file with an object named contextTokenObject, modifications and additions need to be made to this context object from another file (specifically when creating a passport strategy). In the 'passport.js' file, ...

Creating resizable SVG elements using HTML or CSS for dynamic width and height

Is there a way to give my SVG element dynamic width and height in order to display the entire SVG image? For example, take a look at this CodePen link. <svg width="250" height="250" viewBox="0 0 250 250"> Alternatively, .svg { width : 250px; ...

Create a new NVD3 graph with a vertical line added

I am working with a NVD3 graph that displays a simple data set. My goal is to draw a line over the graph in a different color (similar to a cut-off value, which will be at x=5) <meta http-equiv="content-type" content="text/html; charset=UTF8"> <s ...

What could be causing this RangeError to constantly come up while I'm performing a basic math operation in node.js?

My program simply takes two inputs from an HTML form, parses them into text in Node, and then performs a math operation on the two. Strangely, this issue only occurs when dealing with numbers, not strings. Despite the error message indicating an invalid s ...

Dividing the z-index by half of the shape

I am trying to achieve the following shape: https://i.stack.imgur.com/Lr9gv.png So far, I have attempted the following code. How can I combine these elements together? .clal-loader{ display:flex; } .clal-loader div{ border: 10px solid #38477e; b ...

Options for jquery UI autocomplete only appear after the second search

Here is the code snippet I am working with: $("#hifind-find").keyup(function(){ var val = $(this).val(); if (val.length > 1) { var posturl = '/hifind/jquery_ui/autocomplete/'+val; $.post(posturl, function(r) { $("#hifin ...

Unable to retrieve innerHTML from a jQuery element

My current task involves implementing the Google Maps API. The code snippet below is what I have written so far: <div id="map"></div> To inspect the content of $("div#map"), I am utilizing the Google Chrome console. console.log($("div#map")) ...

why doesn't the promise return the record after it has been updated

After completing the form, I proceed to send it as an object to the API NodeJS. The following is the execution function: .post('/create/card', function (req, res) { var rb = req.body, obj = { query: { $set ...

Transfer the value of a variable within the local scope to the dragstart event handler during the dynamic generation of an input element

After going through several similar questions, I couldn't find a solution that applies to my specific case. Here is the loop I am working with: $.each(data.modules, function(i, field) { let $li = $(`<li><div> Name: ${field.name}</div& ...

Unable to initiate script on dynamically appended element

I am facing a similar issue as described in this post: Click event doesn't work on dynamically generated elements , however, the solution provided there did not work for me since the post is a few years old. My problem involves an image carousel that ...

What is the most effective way to send multiple values through the <option> value attribute?

Currently, I am in the process of creating an online shopping item page. To display all the necessary information about an item (such as price, image, name, etc.), I use the 'item_id' to loop through a database containing item info. Additionall ...

The uploading of a file in NodeJS is not possible as the connection was closed prematurely

When I created a website using nodejs, there was a specific page for uploading images to the server. It worked perfectly fine when tested on my computer. However, upon deploying it to the server, the upload functionality stopped working. Upon checking the ...

Tips on choosing a button and applying custom styles with emotion styles in MUI

Looking to apply a margin-right to my button. Currently utilizing mui 5 with Button variant='contained'. I created a custom CSS style using the styled component in mui and targeted the Box. const Wrapper = styled(Box)({ display: 'flex&ap ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

Display the chosen date from the datepicker in the input field

Utilizing a JQuery DatePicker to be constantly displayed, I have assigned it to a div. Despite wanting it to display the selected date in the input box like in this example, it just isn't functioning as desired for me. Is there a way to have the selec ...

What is the process for including the Authorization HTTP header in a JSONP request?

I am attempting to make a GET request to the Yelp API. When I use the code below, I encounter a 401 error. From my research, it seems that setting the authorization in this manner is not possible when requesting JSONP data. However, when I attempt another ...

Building a Node.js authentication system for secure logins

Just diving into node.js and trying to create a user login system, but encountering an error when registering a new user: MongoDB Connected (node:12592) UnhandledPromiseRejectionWarning: TypeError: user is not a constructor at User.findOne.then.user ...

In my attempt to assess the correlation between value 1 and a value in the preceding object, I am utilizing the *ngFor directive

Attempting to compare 2 entries in an *ngFor loop. The code should compare the value at the current object to a value at the previous object. <ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message i ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...