Web standards are here to stay, and with this comes the need for semantic markup. One of the main items of any website is the navigation, in essence a list of links, so it is only right that they should be marked up with a lovely unordered list. Every site I work on now has the main navi (and the sub navi of course!) marked up as a list. I have become very familiar with crafting pretty looking menus with the strong underlying backbone of an unordered list. Trouble is under certain circumstances I find my list gets a little out of control with the amount of whitespace it likes to display.
Let’s start off with some nice clean list markup.
[html]
[/html]
Im sure you are all pretty familiar with an unordered list, so I will spare you the details, next up let’s add some simple styling, as you would if you wanted to make a nice navi.
[css]
ul {
margin:0;
padding:0;
list-style:none;
}
ul li {
margin:0;
padding:0;
display:inline;
}
ul li a {
margin:0;
padding:0;
background-color:#ccc;
}
[/css]
Pretty simple CSS there, I set margin and padding to 0 on everything to more easily reveal the extra white space. Now let’s turn this simple vertical navi into a horizontal one. Simply add display:inline; to the list elements. Preview this new horizontal wonder in your favourite browser and you will see some mysterious whitespace between the anchor elements. This phenomenon is also displayed in this screen shot (flickr).
There you have it, space between elements that have no margin or padding!
Ok, so thats all well and good, you might even be able to cope with the extra whitespace that is being chucked in here but I like my CSS to be a bit more precise, so I’ll show you how to sort this problem.
Try out the following code in your favourite browser.
[html]
[/html]
As if by magic, the white space will be gone! Basically all you need to do to remove those pesky gaps is to write your list on one line and one line only. Trouble with writing the code all on one line is it looks awful. As an alternative, you can drop the last angle bracket (>) on each line, and put it at the start of the following line, as shown on the online demo page, make sure you view the source.
So there we have it, a consistent way of marking up unordered lists. I find I use this technique a lot when working with horizontal navigation. It can also help when using anchors displayed as block, where IE has some issues with how much white space it wants to show.
View the demo page of this technique.
Authors Note: This article was originally published at blog.critical some parts of the article have been tweaked for use here on Devlounge.