Tips for aligning the navigation bar in the center

I recently came across a simple tutorial on w3schools (article) for creating a responsive menu. However, I've been struggling to center it horizontally for the past few days.

Here is the HTML code:

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

And the corresponding CSS:

 /* Remove margins and padding from the list, and add a black background color */
ul.topnav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

/* Float the list items side by side */
ul.topnav li {float: left;}

/* Style the links inside the list items */
ul.topnav li a {
    display: inline-block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of links on hover */
ul.topnav li a:hover {background-color: #111;}

/* Hide the list item that contains the link that should open and close the topnav on small screens */
ul.topnav li.icon {display: none;}

Answer №1

I created a fiddle using the code you provided: https://jsfiddle.net/gqm7zdf9/

An effective solution is to wrap your UL inside a container div where you can apply the background-color. This way, you can position the UL element within its wrapper.

HTML

<div class="nav-wrapper">
    <ul class="topnav">
        ...
    </ul>
</div>

Additional CSS

div.nav-wrapper {
    background-color: #333;
}
div.nav-wrapper ul.topnav {
    display: inline-block;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}


If your target browsers support it, using display:flex offers a simpler solution. Just add the following CSS:

ul.topnav {
    /* ... */
    display: flex;
    justify-content: center;
}

https://jsfiddle.net/gqm7zdf9/1/


You can then proceed with your media queries based on this setup...

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 a Sleek Horizontal Scroll Functionality for Multiple Rows with Bootstrap 5

The container allows scrolling for only half of its content. Afterwards, scrolling affects the navigation panel as well. CSS: .horizontal-scrollable { overflow-x: auto; white-space: nowrap; } HTML: <div class="container hori ...

Achieve full width for container using flexbox styling

In an attempt to develop a category dropdown menu with multiple columns based on the length of the <ul>, I am facing some challenges. For reference, you can view the fiddle that I have created here. The goal is to arrange each submenu item below th ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

Using CSS in combination with AngularJS, you can create a dynamic growth effect for a div element that initially

I am currently using AngularJS to dynamically add divs to a section. My goal is to have each div start with a static width and then grow dynamically as I continue to add more divs. How can I achieve this? The following code is not producing the desired re ...

Ways to make video controls visible following the initial click on the video

I have a collection of videos on my website and I would like them to display with a poster (thumbnail image) initially. The video controls should only appear once the user clicks on the video for the first time. Therefore, when the page is loaded, the cont ...

Techniques for ensuring input validity using JavaScript

One of my form inputs is required: <input type="text" id="input-id" required> After the user submits it, I send the value using ajax and then clear it with $("#input-id").val(""). However, after this action, the input appears invalid. I want to ...

Can Rollup be utilized solely for processing CSS files?

I am curious about whether Rollup can be used solely for processing CSS files, such as css, scss, less, etc. For example, if I have a file called index.css in my src folder (the entry folder) and want Rollup to process it in the dist folder (the output fol ...

arranging three divs in a row, with one div expanding to fill the entire height while the other two divs evenly split the remaining

I am attempting to create a content row consisting of 4 divs: 1 container div 3 divs within the container: 1 image - taking up the full height 2 text - sharing the height, but each on a separate line. It should resemble the following: https://i.sstatic.n ...

Angular CSS: ng-style applied to only one side, the other remains unaffected

I am working on an Angular application that requires a split screen with two halves, each displaying the same array values. The width and height values are set using a service and accessed by a controller. The style is applied using ng-style in the DOM. Ho ...

Tips for making sure custom fonts are loaded before running any JavaScript code

Upon loading my page, I run a JavaScript function to determine if specific text fits within its parent div. If it doesn't fit, then adjustments must be made. The text is styled with a custom font, which can be loaded either through @font-face or Goog ...

What's the best way to customize the color of the text "labels" in the Form components of a basic React JS module?

I have a React component named "Login.js" that utilizes forms and renders the following:- return ( <div className="form-container"> <Form onSubmit={onSubmit} noValidate className={loading ? 'loading' : ''}&g ...

Manipulating CSS animations through JQuery

Currently, my animation is triggered by a :hover event. However, I would like to change it so that the animation starts when a button is clicked. Can someone guide me on how to manipulate the CSS using JQuery? //CSS .mouth{ top: 268px; left: 273px; ...

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

Assign ratings to values based on stars

I am currently facing an issue with implementing a star rating system on my web application. The problem lies in retrieving previously rated values and displaying them as blinking stars. For example, if a user had previously rated something with 4 stars, t ...

Alter the color of the dropdown background when it is changed

Currently, I am utilizing the Semantic UI React CSS library and find myself in need of changing the background color of dropdowns once an option is selected. https://i.sstatic.net/yZBK7.png to https://i.sstatic.net/LxTtT.png <Dropdown placeholder=&apo ...

The <HTML> element is just a bit too big for the screen

When viewing my webpage on mobile, the video background does not fit the screen properly (it fits in landscape orientation). Here is the video tag I am using: <video autoPlay loop muted playsInline className='absolute w-full h- ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Valid ways to ensure that a CSS image expands outside the boundaries of the containing div

I have inserted an image using the following CSS code: .imgtemp { float:right; top:0px; left:0px; overflow:visible; width:100%; } Although I have added the div tag to display it on the page, ...

Navigating from Page 1 to Page 2 and then returning to Page 1 using the browser's back button causes Page 1 to malfunction in NextJS version 13

I am currently using next version 13.4.5 and implementing routing with typescript through /app. On my first page, I have a <Link> (next/link) element that takes me to Page 2. However, when I use the browser back button to return to page 1, the layou ...

Adjust the height of a division dynamically

I have the following HTML snippet: <div id="container"> <div id="feedbackBox"></div> </div> The #feedbackBox div is initially not visible. To center the div, the CSS code is used: #container { position: absolute; widt ...