Thursday 22 September 2011

How to Create a Horizontal Menu through CSS?


In the following part of our CSS menu tutorial we will provide a sample code of a horizontal menu, which formating and functionality is defined using CSS:

<html>
<head>
<title>My horizontal menu</title>
<!--HTML head including the title tag-->
</head>
<body>
<!--HTML body including CSS and the HTML code.-->
<!--The beginning of the CSS code section. -->
<style type="text/css" media="screen">
/* Defines the unordered list attributes:  the list marker is removed, the space between the element border and the element content is set to 0 using the padding property and the space around the elements is also 0. */
#horizontalmenu ul {
padding:0; margin:0; list-style:none;
}
/* Defines the list items' attributes:  the items will float to the left, their position will be relative to the normal one; the space between the element's right border and the element content is set to 20 using the padding property; the items are displayed in a block with a 3D inset border. */
#horizontalmenu li {
float:left; position:relative; padding-right:20; display:block;
border:3px solid #000000; 
border-style:inset;
}
/* Hides the list items of the unordered list. */
#horizontalmenu li ul {
    display:none;
position:absolute;
}
/* When the mouse pointer hovers over the menu elements, the child unordered list items are shown in blocks; the width is set in em units. */
#horizontalmenu li:hover ul{
    display:block;
    background:none;
height:auto; width:8em; 
}
/* No floating elements allowed on either the left or the right side of the elements. */
#horizontalmenu li ul li{
    clear:both;
border-style:none;}
/* the end of the CSS code section; */
</style>
<!--The HTML part of the body section; Here the menu items are entered; They are visualized per the above CSS code definitions; in the div container we specify the unique id, which will be used.-->
<div id="horizontalmenu">
<ul>
  <li><a href="http://siteground.com/">Home</a></li>
  <li><a href="http://www.siteground.com/tutorials/">Tutorials</a>
    <ul>
      <li><a href="http://www.siteground.com/tutorials/cssbasics/index.htm">CSS</a></li>
      <li><a href="http://www.siteground.com/tutorials/flash/index.htm">Flash</a></li>
    </ul>
  </li>
  <li><a href="#">More</a>
    <ul>
      <li><a href="http://www.siteground.com/about_us.htm">About Us</a></li>
      <li><a href="http://www.siteground.com/contact_us.htm">Contact Us</a></li>
    </ul>
  </li>
</ul>
</div>
<!--The end of the body section and the html file.-->
</body>
</html> 
Please note that the above code is tested on the latest version of Mozilla Firefox. It should work normally on all new browsers, which support the hover functionality.

No comments:

Post a Comment