Friday, July 16, 2010

CSS Navigation Menu Using Floats

So far, we floated the div element for layout, the img element for both layout and styling of a page and now I want to show you how to float list items in an unordered list, ul, for navigation.

We give the ul an id, #menu and fill the list elements with our menu headings, About, Blog, Portfolio, Exhibitions, Awards, Bio and Contact. The navigation menu being clickable, we will wrap each menu item in an "a" element. We'll give the background of the body a color and a minimum width.

<style type="text/css">
body {of 
  background-color: #eceec5;
  min-width: 1100px;
}
</style>

<body>
<ul id="menu">
   <li ><a href="#">About</a></li>
   <li><a href="#">Blog</a></li>
   <li><a href="#">Portfolio</a></li>
   <li><a href="#">Exhibitions</a></li>
   <li><a href="#">Awards</a></li>
   <li><a href="#">Bio</a></li>
   <li><a href="#">Contact</a></li>
</ul>
</body>
</html>          

CSS Float Unordered List

An unordered list comes with bullets by default which we don't need. We also want our menu items to appear side by side. How do we make a CSS unordered list horizontal? Very easy. We will float each li to the left with a margin of 21 pixels in between them. We reset padding to zero and give a large left margin of 400 pixels to push the menu to the right side.

#menu {
  list-style: none;
  margin: 45px 0 0 400px;
  padding: 0;
}

#menu li {
  float: left;
  margin: 0 0 0 21px;
  padding: 0;
} 

CSS Float Unordered List
Floating worked just fine. The space between each menu item is 21 pixels. We can dress it up by styling with a fancier font. I am going to use a Google font by linking in their style sheet for "Kaffeesatz" font. Text shadow is available in CSS 3.0 so I included that in my styles. In the hover state, I am going to switch the text color from red to black and draw a thick line below the menu item to make the menu appear more interactive.

When using <a> tags in this menu, I set the display property of the a's to block. By default, a's are inline. While leaving them as inline actually works in many modern browsers, it's a better idea to set them to block. With inline elements, CSS doesn't allow you to control dimensions using width and height, nor does it allow to specify vertical margins and padding. So by making it a block element, we are able to take control of the dimensions and rendering of the elements in a way that inline formatting does not allow.

<link rel="stylesheet" 
        type="text/css"  href="http://fonts.googleapis.com/css?family=Yanone Kaffeesatz">  
  
<style type="text/css">
#menu li a {
  font-family: 'Yanone Kaffeesatz', sans-serif;
  font-size: 29px;
  color:  #ac1212;
  text-decoration: none;
  text-shadow: 1px 1px 1px #aaa;
  display: block;
}

#menu li a:hover {
  color: black;
  border-bottom: 3px solid #ac1212;
}

Our navigation menu with floats:

CSS Float Unordered List

Post a Comment

Note: Only a member of this blog may post a comment.