Right-aligned menu

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:

So, 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:

  1. Keep the list items floated left, to keep them in order, and on the same horizontal
  2. Float the list to the right to create the required alignment
ul { float: right; }
li { float: left; }

Comments

Thu 31 Dec 2009 10:44

Stargazer

Stargazer said:

All elements with "float" must have a specified width. The behavior of floats without a constant width is undefined, and therefore unpredictable.

Thu 31 Dec 2009 17:48

Five Minute Argument

Five Minute Argument said:

@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.

Mon 4 Jan 2010 06:47

Stargazer

Stargazer said:

That doesn’t necessarily mean that its ok to do. Internet Explorer has a history of ignoring the CSS standard.

Mon 4 Jan 2010 11:58

Five Minute Argument

Five Minute Argument said:

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?

Leave a comment