Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally center an unordered list of unknown width?

It is common to have a set of links in a footer represented in a list, such as:

<div id="footer">     <ul>         <li><a href="#">Home</a></li>         <li><a href="#">About</a></li>         <li><a href="#">Contact</a></li>     </ul> </div> 

I want everything inside div#footer to be centered horizontally. If it was a paragraph, you would just easily say: p { text-align: center; }. Or if I knew the width of the <ul> I could just say #footer ul { width: 400px; margin: 0 auto; }.

But how do you center the unordered list items without setting a fixed width on the <ul>?

EDIT: clarification - the list items should be next to each other, not below.

like image 736
philfreo Avatar asked Nov 08 '09 02:11

philfreo


People also ask

How do I center an unordered list horizontally?

Just give the list centered text (e.g. ul. nav { text-align: center; } ) and the list items inline-block (e.g. ul. nav li { display: inline-block; } ). If you want to do it with margin for whatever reason, look into width: fit-content; .

How do I center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element. Now, add the style to the div class and use the text-align property with center as its value.


2 Answers

The solution, if your list items can be display: inline is quite easy:

#footer { text-align: center; } #footer ul { list-style: none; } #footer ul li { display: inline; } 

However, many times you must use display:block on your <li>s. The following CSS will work, in this case:

#footer { width: 100%; overflow: hidden; } #footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; } #footer ul li { position: relative; float: left; display: block; right: 50%; } 
like image 200
philfreo Avatar answered Sep 29 '22 17:09

philfreo


Use the below css to solve your issue

#footer{ text-align:center; height:58px;} #footer ul {  font-size:11px;} #footer ul li {display:inline-block;} 

Note: Don't use float:left in li. it will make your li to align left.

like image 45
Yuvaraj Avatar answered Sep 29 '22 17:09

Yuvaraj