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

Determine whether the request was made using ajax or traditional non-ajax methods

While testing the PHP code below, I noticed that the headers in the request do not indicate that it is JavaScript sending the request instead of a non-JavaScript user: Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 AlexaToolba ...

Deactivating Node.js files in vsCode for client-side JavaScript files

I'm facing a major challenge when it comes to coding with JavaScript. I have a JavaScript file that is using Node.js, which means I am unable to manipulate the DOM elements. Take this code snippet for example: var form = document.getElementsByClassNa ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

Switch div and expand/shrink the rest

Apologies for what might seem like a trivial question, but after working for a few hours now, I'm finding it difficult to wrap my head around this. My initial instinct is to handle this by manipulating the entire div structure with JavaScript, but I c ...

"Displaying mongoose date in the HTML5 input type date format (dd/mm/yyyy) is a simple process that can

I have a structured data in MongoDB as shown below: var Person = new Schema({ "Name": { type: String, required: true }, "DOB": { type: Date, "default": Date.now } }); An instance of this schema is created using NodeJs with mongoose ODM: { "N ...

CSS3 Feature: Chevron-shaped banner with jagged edges

I'm currently working on building a unique chevron-style banner using CSS3, but I've run into some aliasing problems specifically in Chrome. Despite trying to utilize the -webkit-backface-visibility: hidden attribute, I still can't seem to r ...

JavaScript Empty Input Field when Duplicating Node

I am seeking advice on how to clear the textboxes when an HTML form is cleared. The following JS code runs onclick: var counter = 0; function moreField() { counter++; var newFields = document.getElementById('readroot').cloneN ...

Internet Explorer struggling to function due to JavaScript errors

While Chrome and Firefox breeze through the page, it seems to hang for an eternity in Internet Explorer. Here is the problematic page: ============= Error Details: User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2 ...

Incorporating promises with ajax to enhance functionality in change events

Consider the scenario where you trigger an ajax request upon a change event in the following manner: MyClass.prototype.bindChangeEvent = function(){ $(document).on('change', '#elementid', function(){ var $element = $(this); $ ...

Executing a Node.js program using the command line without having to type out the word 'node'

I am currently working on a Node.js package that includes a command-line utility. Right now, alacon.js is situated in the root of the package. To execute this utility, I have to use the word node followed by the utility's name, like so: node alacon ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

Error: Ajax unable to parse JSON - property 'name' does not exist in the object

When accessing my report.php file, it returns a json data. Here is the snippet of javascript code I am using to try and read the json: <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> $(document).ready(function ...

Setting the initial state with an undo action in React: a step-by-step guide

Is it possible to display a snackbar with an undo action when dragging and dropping events in a react-big-calendar? https://i.stack.imgur.com/QFmYA.png I am trying to implement functionality where clicking on the undo action will revert the event back to ...

PHP code in Wordpress incorporating an Ajax request

Does anyone know how to fetch user data as a string using ajax in WordPress? I think I understand the basic concept PHP This code goes in my functions.php file add_action('template_redirect', 'edit_user_concept'); function edit ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

A guide to updating a button in Angular:

Currently, I have implemented a directive that displays 3 tabs at the bottom. However, I am curious to know if it is possible to swap out "exterior" for "interior" based on whether I am on the exterior or interior page. For example, when on the exterior ...

Ajax is displaying some unusual behavior

Currently, I am working on an ajax request to check if a specific combination of username or password exists. <script> $("form").submit(function(e){ e.preventDefault(); //send data to ajax file now $.ajax({ type: 'POST ...

Transferring files and information using the Fetch API

I am currently working on a React application and I have defined the state of my application as shown below: const [book, setBook] = useState({ title: '', cover: {} numberPages: 0, resume: '', date: date, }); The & ...