How to center text inside li element inside unordered list

This list works fine for me, but the text inside the <li> elements is not centered.

<li> should automatically resize the content.

 #nav-menu { font-family: Verdana, Arial, Helvetica, sans-serif; height: 30px; background-image: url(../img/menu_bg.png); background-repeat: repeat-x; border-bottom: dotted thin #666666; border-top: dotted thin #666666; text-align: center; width: 800px; } #nav-menu ul { list-style: none; padding: 0; margin: auto 0; } #nav-menu li { float: left; border-right: dotted thin #666666; list-style: none; padding: 0.5em 2em 0.5em 0.75em; } #nav-menu li a { line-height: 1.5em; color: #333333; text-decoration: none; font-size: 12px; font-weight: bold; display: block; } 
 <div id="nav-menu"> <ul> <li class="current_page_item"><a href="#" title="Home">Home</a> <li class="current_page_item"><a href="#" title="Home">Home</a> <li class="current_page_item"><a href="#" title="Home">Home</a> <li class="current_page_item"><a href="#" title="Home">zxczczxczHome</a> </ul> </div> 
+6
css text html-lists
source share
2 answers

As long as you assign unequal padding values ​​to the left and right of li ( 0.75em and 2em respectively), the text cannot be centered because you force it off-center padding .

If you indent to: padding: 0.5em 1em; ( 0.5em top and bottom, 1em left and right), then it can be centered.

 #nav-menu { font-family: Verdana, Arial, Helvetica, sans-serif; height: 30px; background-image: url(../img/menu_bg.png); background-repeat: repeat-x; border-bottom: dotted thin #666666; border-top: dotted thin #666666; text-align: center; width: 800px; } #nav-menu ul { list-style: none; padding: 0; margin: auto 0; } #nav-menu li { float: left; border-right: dotted thin #666666; list-style: none; padding: 0.5em 1em; } #nav-menu li a { line-height: 1.5em; color: #333333; text-decoration: none; font-size: 12px; font-weight: bold; display: block; } 
 <div id="nav-menu"> <ul> <li class="current_page_item"><a href="#" title="Home">Home</a></li> <li class="current_page_item"><a href="#" title="Home">Home</a></li> <li class="current_page_item"><a href="#" title="Home">Home</a></li> <li class="current_page_item"><a href="#" title="Home">zxczczxczHome</a></li> </ul> </div> 

JSFiddle demo of the above.

+10
source share

If you want a different size, change the property of the right to right or left so that it is the same as the other:

 padding: 0.5em 2em 0.5em 2em; 

or

 padding: 0.5em 0.75em 0.5em 0.75em; 

I played a little with him: http://jsfiddle.net/Q32hn/ Remember to always close ListItems

+6
source share

All Articles