A navigation area on websites is an important factor in providing visitors a user-friendly experience allowing them to navigate through different web pages.
The majority of websites have them, and therefore styling navigation menus is a useful HTML/CSS skill to have. There are of course many different styles of navigation menus you could create, however this post will just be focusing on the basics of horizontal and vertical menus.
The most simple example of a horizontal menu can be summarised with the following markup:
<nav class="nav">
<ul>
<li><a href="/link-1">Link 1</a></li>
<li><a href="/link-2">Link 2</a></li>
<li><a href="/link-3">Link 3</a></li>
</ul>
</nav>
There are two CSS methods that you can use to horizontally style the menu: by floating or using inline list items.
One of the advantages of using float: left
and display: inline
is that they can both be used for IE 6/7, however floats have to be cleared, and the inline rule isn’t advised to be used in modern CSS.
If you are not worried about supporting IE 6/7, you can use display: inline-block
, which works consistently well across browsers.
All three of the suggested techniques will correctly display the menu items on one line, and their CSS can be seen below.
.nav ul li {
float: left;
}
.nav ul li {
display: inline;
}
.nav ul li {
display: inline-block;
}
Some menus choose to have their navigation displayed vertically, down the sides of the web page.
The CSS for this is actually easier than horizontal menus, as the browser will by default ensure that each list item shows on one line. Some users may specify the display: block
rule to reinforce this behaviour.
If you need to add CSS rules that only apply when the cursor has hovered over a menu item, should the rules be added to the list item hover over or the anchor tag hover over?
Usually the hover over effects are added to the anchor tag within the list item, so for example if you wanted to change the colour of the text when hovering over the list item, you could write the following.
.nav ul li a:hover {
color: red;
}
CSS should also be applied to the anchor tag when using padding to add spacing between the list items. Usually this will come along with a display: block
for the anchor.
.nav ul li a {
display: block;
padding: 8px 16px;
}