Horizontal Menu Using UL

A convention in web design is to use an unordered list for navigation. There is a certain logic to that, as each menu is technically a list of links.

Creating a vertical menu is rather straightforward, but turning an unordered list into a horizontal menu requires a bit more work.

Changing the list

The first thing we'll need to do is to change the UL so that it doesn't behave like a set of bullet points anymore. That means changing the list-style-type to none. We'll also se the margins and padding to zero and make sure the overflow is set to hidden. According to the W3Schools: "The overflow property specifies whether to clip content or to add scrollbars when the content of an element is too big to fit in a specified area."

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #FCF;
}

Going horizontal

Next, we'll need to get the list items to be horizontal. There are two options for this, we can change the block element to behave as an inline element (display: inline;), or we can float the list items to the left. We'll do the latter.

li {
float: left;
}

Next, we need to control the behaviour of the link within the list item. That will need to display as a block element (remember a link is an inline element by default).

li a {
display: block;
color: #444;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

If you want a hover effect, you'll need to add that too.

li a:hover {
background-color: red;
color: white;
}

Wait, won't this affect all UL tags?

Yes. The way we've written it will cause all <ul> tags to behave like the menu, so we should be more specific about things and ensure this only happens where we want.

We're doing our main menu here, so let's include the nav selector before each rule.

Here's what it looks like all in one go:

nav ul {
list-style-type: none;
margin: 0;
padding: 0px 0px 0px 290px;
overflow: hidden;
background-color: #FCF;
}

nav li {
float: left;
}

nav li a {
display: block;
color: #444;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

nav li a:hover {
background-color: red;
color: white;
}