Practice Exams for Windows

Practice Exams for Windows

Saturday, 4 October 2008

My pure CSS drop-down menu

UPDATE: A better version of this is available here.

I've finally successfully created a pure CSS drop-down menu. Up until now I have avoided drop-down menus or used old table-based javascript menus. I've stripped the code right out to the bare minimum code required to make it work. I've tested the code in the following browsers:
  • Mozilla Firefox 2
  • Internet Explorer 7, 8 Beta 2
  • Apple Safari
  • Google Chrome
Ok, let's look at the code.

Here is the CSS:
* {margin: 0; padding: 0;} /* reset all margins and padding */
#navigation #item1 {float: left; width: 150px;}
#navigation #item2 {float: left; width: 150px;}
#navigation #item3 {float: left; width: 150px;}
#navigation li {list-style: none;}
#navigation ul {display: none;}
#navigation *:hover > ul {display: block;}
You can make the code even lighter by using more wildcards but I didn't have time to test the effects, have a play with the #navigation * selector ... if you like.

Now for the XHTML:

<div id="navigation">
<div id="item1">
<a href="item1.html">Item 1</a>
<ul>
<li><a href="item1-1.html">Item 1.1</a></li>
<li><a href="item1-2.html">Item 1.2</a></li>
</ul>
</div>
<div id="item2">
<a href="item2.html">Item 2</a>
<ul>
<li>Item 2.1</li>
<li>Item 2.2</li>
</ul>
</div>
<div id="item3">
<a href="item3.html">Item 3</a>
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li>
</ul>
</div>

</div>

I didn't mess around too much. I know it works on the browsers I need it to work on so I didn't bother doing any further changes or testing.

IMPORTANT: The code will NOT work without the correct doc-type. Here is the full source code to make it easy for everyone (be sure to move your CSS to an external stylesheet when you are ready to use this on a live site):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
<!--
* {margin: 0; padding: 0;}
#navigation {}
#navigation #item1 {float: left; width: 150px;}
#navigation #item2 {float: left; width: 150px;}
#navigation #item3 {float: left; width: 150px;}
#navigation li {list-style: none;}
#navigation ul {display: none;}
#navigation *:hover > ul {display: block;}
-->
</style>
</head>

<body>
<div id="navigation">
<div id="item1">
<a href="item1.html">Item 1</a>
<ul>
<li><a href="item1-1.html">Item 1.1</a></li>
<li><a href="item1-2.html">Item 1.2</a></li>
</ul>
</div>
<div id="item2">
<a href="item2.html">Item 2</a>
<ul>
<li>Item 2.1</li>
<li>Item 2.2</li>
</ul>
</div>
<div id="item3">
<a href="item3.html">Item 3</a>
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li>
</ul>
</div>

</div>
</body>
</html>

1 comment:

  1. I knew I was going in the right direction with mine.. turned out kinda wonky though. But well done for getting it down packed

    ReplyDelete