Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu:

nav {  
    height: 40px;  
    width: 100%;  
    background: #F00;  
    font-size: 11pt;  
    font-family: Arial;
    font-weight: bold;  
    position: relative;  
    border-bottom: 2px solid #FFFFFF;  
}  
nav ul {  
    padding: 0;  
    margin: 0 auto;  
    width: 600px;  
    height: 40px;  
}
nav li {  
    display: inline;  
    float: left;  
}  
.clearfix:before,  
.clearfix:after {  
    content: " ";  
    display: table;  
}  
.clearfix:after {  
    clear: both;  
}  
.clearfix {  
    *zoom: 1;  
}  
nav a {  
    color: #000000;  
    display: inline-block;  
    width: 100px;  
    text-align: center;  
    text-decoration: none;  
    line-height: 40px;  
}  
nav li a {  
    border-right: 1px solid #FFFFFF;  
    box-sizing:border-box;  
    -moz-box-sizing:border-box;  
    -webkit-box-sizing:border-box;  
}  
nav li:last-child a {  
    border-right: 0;  
}  
nav a:hover, nav a:active {  
    background-color: #000000;
    color:#FFFFFF;  
} 
nav a#pull {  
    display: none;  
}  
@media screen and (max-width: 600px) {  
    nav {   
        height: auto;  
    }  
    nav ul {  
        width: 100%;  
        display: block;  
        height: auto;  
    }  
    nav li {  
        width: 50%;  
        float: left;  
        position: relative;  
    }  
    nav li a {  
        border-bottom: 1px solid #FFFFFF;  
        border-right: 1px solid #FFFFFF;  
    }  
    nav a {  
        text-align: left;  
        width: 100%;  
        text-indent: 25px;  
    }  
}  
@media only screen and (max-width : 480px) {  
    nav {  
        border-bottom: 0;  
    }  
    nav ul {  
        display: none;  
        height: auto;  
    }  
    nav a#pull {  
        display: block;  
        background-color: #FF0;  
        width: 100%;  
        position: relative;  
    }  
    nav a#pull:after {  
        content:"";  
        background: url('nav-icon.png') no-repeat;  
        width: 30px;  
        height: 30px;  
        display: inline-block;  
        position: absolute;  
        rightright: 15px;  
        top: 10px;  
    }  
}  
@media only screen and (max-width : 320px) {  
    nav li {  
        display: block;  
        float: none;  
        width: 100%;  
    }  
    nav li a {  
        border-bottom: 1px solid #FFFFFF;  
    }  
}  

Is there a way to center align the links within the li elements?

For a visual representation of the menu, you can view it on this fiddle: http://jsfiddle.net/zJq52/

Answer №1

If I were to tackle this, my approach would be:

nav ul {  
    padding: 0;  
    margin: 0 auto;  
    width: 600px;  
    height: 40px;  
    text-align: center; // included text-align
}
nav li {  
    display: inline; // removed float from here 
}  

SEE THE DEMO HERE

An Update: For a responsive layout, try this:

nav a {  
    color: #000000;  
    display: inline-block;  
    width: auto;  // changed it to flexible width instead of fixed 100px 
    text-align: center;  
    text-decoration: none;  
    line-height: 40px;  
}  

TRY THIS UPDATED DEMO

Final Version Released: Check out the final version here!

FINAL DEMO VERSION

Answer №2

Check out the live demo here

Make a simple adjustment to the CSS for nav a:

nav a {
   text-align: center;
   width: 100%;
}

There are currently two instances of nav a. Combine them into one and make these modifications:

nav a {  
    color: #000000;  
    display: inline-block;
    text-align: center;  
    text-decoration: none;  
    line-height: 40px;  
    width: 100%;  
    padding: 0 10px; 
}

View the updated code snippet and output by visiting this jsFiddle link.

If you want to center the buttons in a row within the horizontal bar, add a width property to the <ul> element with a new class:

<ul class="clearfix cont">
. Apply styling within a media query to avoid affecting other layouts:

@media screen and (min-width: 600px) {  
   .cont {width: 380px;}
}

See the finalized version on this jsFiddle link.

Answer №3

Uncertain of your exact query, but if you are referring to centering all the list items in relation to their parent, adjust the width from 600px to 400px

nav ul {
padding: 0;
width: 400px;
height: 40px;
display: block;
margin: 0 auto;
position: relative;
}

See a demonstration here: - http://example.com/demo

Answer №4

EXCLUSIVE DEMO Sample Link

Discover the optimal approach to achieve your desired outcome

Customized CSS-

nav ul {  
    padding: 0;  
    margin: 0 auto;
    width:800px;
    text-align:center;
    height: 40px;  
}
nav li {  
    display: inline-block;  //recommended use of inline block
}  
nav a {  
    color: #000000;  
    display: inline-block;  
    padding: 0 20px; //prefer padding over width
    text-decoration: none;  
    line-height: 40px;  
} 

Answer №5

Choosing a float may not always be the best decision.

In your example, setting a fixed width of 600px for the "nav ul" element seems odd when you only have 4 elements with widths around 100px each. It makes centering difficult...

Instead of using floats and clearfixes, I suggest the following approach:

nav {
  margin: 0 auto;
  text-align: center;
}
nav ul {
  margin: 0 auto;
  text-align: center;
  width: auto;
}
nav ul li {
  display: inline;
  display: inline-block;
}
nav ul li a {
  /*width: 100px;*/
  width: auto;
  padding: 0 10px;
}

Here is an example of how it could be done: http://jsfiddle.net/xewl/4CrdN/1/

I noticed that you have other versions that somewhat achieve the intended result: http://jsfiddle.net/zJq52/6/ In this version, there isn't a set width for "nav ul li a." But why is the width of "nav ul" 400px?

Answer №6

Give This a Shot

nav li a {  
border-right: 1px solid #FFFFFF;  
box-sizing:border-box;  
-moz-box-sizing:border-box;  
-webkit-box-sizing:border-box;  

text-align:center; /* New addition */
}  

Answer №7

Extremely easy.

To achieve center alignment, include text-align: center in the nav ul style and remove float: left from the nav li.

nav ul {  
    padding: 0;  
    margin: 0 auto;  
    width: 600px;  
    height: 40px;  
    text-align: center;
}
nav li {  
    display: inline;   
} 

You can view the updated fiddle here: http://jsfiddle.net/qwUF7/

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

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Transforming jquery code into angularjsAre you looking to migrate your

I am currently struggling with converting a jQuery function into an AngularJS function. Here is the specific code snippet: $('p').each(function() { $(this).html($(this).text().split(/([\.\?!])(?= )/).map( function(v){return '< ...

Reducing an array group using index in JavaScript: A beginner's guide

Do you have coding questions? Check out this sample array group: myArray = { tab1 : [], tab2 : [], tab3 : [], tab4 : [] } I'm looking to always retain the first tab (tab1) and an additional tab based on an index (ranging from 2 to 4) For instance, ...

Utilizing React to create an infinite loop, where an onClick event triggers an image change that updates the source of

I'm experiencing an infinite loop in my React application. I'm attempting to include a previous Image and next Image button in the development stage using an image tag. However, when my component loads up, I encounter errors. Does anyone have a ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Disabling and enabling a link before and after an AJAX call using jQuery

I have been trying to disable a link before making an ajax call and then re-enable it right after receiving the response. However, my current approach doesn't seem to be working as expected: jQuery(this).prop('disabled', false); Here is my ...

Hyperlink -> Boundary

Our homepage features various elements as part of the menu. Each element consists of a picture, title, and small description. The issue is that these menu items always display a border when the mouse hovers over them, despite attempts to hide it. You can ...

Employing live labels on a Morris Bar Chart

I'm using the Morris Bar Chart to showcase the sales of different products. To enhance user experience, I want to display dynamic labels when hovering over the bars. The data is being fetched through PHP. array('product' => $row['pr ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

Utilizing the dynamic capabilities of Ajax in tandem with the popular Jquery and Code

tag, I have a scenario where a controller is sending data from two functions in a model to a view. This involves retrieving the results of 'waiting' and 'beingseen' functions and passing them to the 'studentqueue/studentqueue' ...

Background image not visible on Firefox and Chrome when using a DIV element

I'm encountering an odd issue where my DIV background isn't showing up in Firefox and Chrome, but it looks fine in IE. I've searched on several places like Stackoverflow for solutions to this problem, but none of them have worked for me so f ...

Tips for preserving user input from HTML into a text file and then reloading it back into the HTML document

I have recently created a character sheet for a game using HTML. The HTML file is mainly comprised of various input tags such as <input type="text">, <input type="number">, <input type="checkbox">, <input type="radio">, <select&g ...

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...

React is having difficulty locating a specific module

I've been attempting to install the parallax library from https://github.com/wagerfield/parallax/. I have gone through the documentation and even found a sample usage in JavaScript. Planning to integrate it into React, based on the sample code and Rea ...

There was an error in parsing the JSON data due to an unexpected token "u" at the beginning of the string

I've been working on improving my JavaScript skills, but I hit a snag with an error message that reads "Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse". var requestData = new XMLHttpRequest(); requestData.open('GET& ...

I'm looking for assistance on how to set the minimum height using jQuery. Can anyone provide

My attempt to use the minHeight property in one of my divs is not successful, and I am unsure why... <div id="countries"> <div class="fixed"> <div class="country" style="marging-left:0px;"></div> <div class="country"&g ...

The input-group-btn is positioned to the right of the field, appearing to float

The input-group-btn for the targetDate field remains fixed on the right side of the input group despite screen width variations until I introduce the automatically generated CSS from the hottowel generator. I require assistance in identifying which aspect ...

Cause $.ajax to fail

Can you believe it, I have a peculiar request. I need to find a way for $.ajax to fail so I can test my fail trigger. Check out this snippet of jQuery code: $(document).ready(function () { $("#trigger").on("click", function () { $.ajax({ ...

Using the mt-downloader module in a Node application is a straightforward process

Hey there, I'm looking to incorporate the Multi downloader module into my project. I've checked out the GitHub link, but unfortunately, there are no examples provided on how to actually use this module. I came across this example and tried implem ...

Tips for implementing jQuery on HTML loaded post document.ready():

I've encountered a scenario where I have multiple HTML elements being rendered by a JavaScript function on the page: <a href="#" class="test1">Test</a> <a href="#" class="test2">Test</a> <a href="#" class="test3">Test< ...