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

Moving the content of a div outside the browser window within an electron application

After cloning the electron quickstart app from GitHub, I noticed that it creates a browser window to display HTML content. The code snippet mainWindow = new BrowserWindow({width: 800, height: 600}) exemplifies this behavior. As I work on creating an app ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

Sharing stickers with Discord.js version 13

I have encountered an issue while trying to forward messages sent to my bot via DM. Everything is functioning smoothly, except for sending stickers. Whenever I attempt to send a message with a sticker, an Error DiscordAPIError: Cannot use this sticker is ...

Adding content to a div element using jQuery is a simple and effective way to

I am attempting to incorporate the content from a specific div into a jQuery function. Kindly refer to the details below: This is the content I want to include: <div id="year">2020</div> My objective is to replace the '2019' within ...

Node.Js error: "The requested resource does not have the 'Access-Control-Allow-Origin' header present."

This particular query shares similarities with others, however there is a perplexing difference that is causing it to malfunction. Previously, my JavaScript was able to fetch 6 json files without any issues. In Node.JS, I have configured cors and headers ...

What is the best way to populate a table with form text fields using jQuery?

I have a scenario where I need to toggle between two forms. The initial form #form1 includes input fields for month and year, along with a search button. The secondary form #form2 consists of a table that needs to be populated based on the month and year s ...

Using jQuery, the image name will be displayed once it is selected

When I click on the image and then on the Add button, the image name should be displayed in an alert message. However, it is not working as expected. Below is the code that I have tried so far. If I click on the Chocolate image, the alert message should di ...

A guide on seamlessly incorporating FlotJs functionalities into a ReactJs application

Having trouble integrating Flot charts into React due to a '$.plot' is not a function error. Here's the code I'm using: Script tags Index.html <script src="dist/libs/js/jquery.min.js"></script> <script src="dist/libs/js ...

Interfacing shared memory between a C++ and JavaScript program

Is it feasible to have shared memory that both a C++ program and a JavaScript program can access simultaneously? The goal is for the C++ program to write to memory while the JS program reads from the same location. ...

If there are multiple instances of the component, it may not function properly

I have implemented a Vue component as shown below: <script setup lang="ts"> import { PropType } from "nuxt/dist/app/compat/capi"; interface Star { id: string; value: number; } const stars: Star[] = [ { id: &qu ...

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

JavaScript Filtering JSON Data Based on Date Range

I am attempting to filter a basic JSON file based on a specified date range, with both a start date and an end date. Below is the function I have created for this task: var startDate = new Date("2013-3-25"); var endDate = new Date("2017-3-2 ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

Establishing a proxy server to support the development of a Create React application

Recently, I initiated a react application with the help of create-react-app. Following that, I executed the npm run eject script to unlock access to all files. Subsequently, I incorporated express and crafted a server.js file which is located on the same l ...

What's the issue with ng-click not functioning properly?

My goal is to create a directive called "myDisabled" in AngularJS version 1.1.5 since the ng-disabled functionality is not available in this version. Here is the code for the directive: tableApp.directive('myDisabled', function($compile) { retur ...

Running two different versions of the same React-App concurrently: A step-by-step guide

I currently have a react-app that was created using create react app. There is an older branch that is approximately 1 month old, as well as a current branch. I am interested in running both branches simultaneously and making changes to the current branch ...

Using jQuery and regular expressions to replace placeholders with dynamic values

I need some help with replacing custom variable tags in a content block using values from an array. Currently, my code successfully replaces variables that look like %([variable_name])%, but I also need it to replace variables in the format <%[variable_ ...

JavaScript and Ajax are functioning properly in Mozilla Firefox, however there seem to be some compatibility issues with Google Chrome

I have a form that serves the dual purpose of registration and login, and I am using JavaScript Ajax to submit it. While it works smoothly in Mozilla Firefox, it fails in Chrome and IE. The goal is to execute an AJAX and PHP script that checks the databa ...

Is there a way retrieve all named HTML tags and store them in an array?

In need of assistance with parsing data from a page that is formatted as follows: <tag>dataIwant</tag> <tag>dataIwant</tag> <tag>dataIwant</tag> <othertag>moarData</othertag> <othertag>moarData</oth ...