How to style a right-aligned menu, the easy way.
Since the modern web design era began, and we all learnt to separate our content from our styling, there’s been a pretty standard way of marking-up and styling a horizontal navigation menu. The menu itself, consisting of a list of links, is marked-up like so:
<ul>
<li><a href="#">Apple</a></li>
<li><a href="#">Banana</a></li>
<li><a href="#">Cherry</a></li>
</ul>
and styled as follows:
ul { overflow: hidden; margin: 0; padding: 0;
list-style-type: none; }
li { float: left; margin-bottom: 0; margin-right: 0.5em;
background: #eee; line-height: 1; border: 1px solid #ddd; }
a { padding: 0.25em 0.5em; display: block; border: none; }
with the following result:
Much of that CSS is necessary to tweak a browser’s default values for padding, margins, and list style (the bullets) for those elements. There’s also a bit of style to emphasise the ‘menu-like’ aspect of these elements; this will vary between designs and a very simple look is presented here for demonstration.
In terms of the layout, there’s very little in the way of necessary adjustment, namely:
li { float: left; } to align the individual list items on the same horizontalul { overflow: hidden; } to instruct the overall list to stretch to surround its floated childrena { display: block; } to ensure the links generate block boxes to which padding can be appliedSo, when it comes to aligning that menu to the right of its container (often the entire page), it should just be a case of right-floating those list items, right?
li { float: right; }
Wrong. Unfortunately, the menu items are now displayed in reverse order, since the first is floated over to the right edge, the next is floated onto its left edge, etc.
The solution is pretty straight-forward:
ul { float: right; }
li { float: left; }
@Stargazer: I think this is a common misunderstanding: it’s one of the issues that frequently trips me up, but — apparently — floats do not need a width in CSS 2.1. For floated elements, the spec states:
if 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.
and, in the 'changes from CSS2' appendix:
Floats are no longer required to have an explicit width.
That doesn’t necessarily mean that its ok to do. Internet Explorer has a history of ignoring the CSS standard.
Yeah, Internet Explorer < 8 certainly has many problems with floats, not just restricted to width. Do you know of specific examples of IE mistreating floats without explicit widths?
Thu 31 Dec 2009 10:44
Stargazer said:
All elements with "float" must have a specified width. The behavior of floats without a constant width is undefined, and therefore unpredictable.