Tallboy
Tallboy

Reputation: 13467

Using display:inline for centered menus vs display:block

Say you have a horizontal, graphical nav menu where each menu item is variable width (controlled by padding rather than a width to the <li> element). This means you can't truly know the width of the ul (in order to center it) because the text is different sizes in different browsers.

Up until now I would either

A) Just eye it and use margin-left on the ul

B) use jquery to calculate the width and then set set it as an inline-style so that the width can be set, and then it can be margin: auto'd.

But someone just told me I can use display: inline and it works fine, without using float, and it always centers? has anyone heard of this? he's kind of new and can't quite explain it so i'm curious what you guys think. He says he thinks text-align: center. I dont see how this would work on a menu though.. which is not text?

Upvotes: 1

Views: 166

Answers (2)

avramov
avramov

Reputation: 2114

Set the ul and lis to display:inline or display:inline-block, and set the ul's container to text-align:center. You might have to add zoom:1 for some older versions of IE to work properly with inline-block.

Suggested reading:

Upvotes: 0

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57690

Any text level element can be centred. It'll be centered according to its parent element. Which should be a block level element.

The following menu can be centred,

<ul id="ul">
<li>one</li>
<li>two</li>
<li>January</li>
<li>September</li>
</ul>

Using this CSS

ul#ul{text-align:center;}
ul#ul li{display:inline;}

See this jsfiddle to get an idea

Upvotes: 2

Related Questions