Wednesday, December 8, 2010

Drop Down Menu Simple Solution Using UL(Un-numbered List) + CSS



Here are the sample codes in HTML and CSS (important code shown in red):


<style type="text/css">
#main_menu ul {padding: 0; position: absolute;}
#main_menu li {float: left; position: relative; }
#main_menu a {text-decoration: none;}

.main_item {list-style: none; border: 1px solid black; background-color: #DDEEFF; text-decoration: none;}
.item {list-style: none; border: 1px solid black; background-color: #FFEEDD; width: 100%; text-decoration: none; text-align: center;}

#main_menu li:hover ul, li.over ul {display: block;}
.sub_menu {display: none; left: 0; position: absolute;}

</style>

<body>

<ul id="main_menu">

<li class="main_item">
<a href="">  Main Item 1  </a>
<ul class="sub_menu">
<li class="item"><a href="">Test Item A</a></li>
<li class="item"><a href="">Test Item B</a></li>
<li class="item"><a href="">Test Item C</a></li>
<li class="item"><a href="">Test Item D</a></li>
</ul>
</li>

<li class="main_item">
<a href="">  Main Item 2  </a>
<ul class="sub_menu">
<li class="item"><a href="">Test Item E</a></li>
<li class="item"><a href="">Test Item F</a></li>
<li class="item"><a href="">Test Item G</a></li>
<li class="item"><a href="">Test Item H</a></li>
</ul>
</li>

</ul>


</body>




I was always amazed by how people use <UL> with CSS to create drop down menu as I always use layers with visibility in CSS to create menu. After knowing this trick using <UL> with CSS, it's a lot simpler than the method I used formerly.

In fact, <UL> can easily forced to line up items next to each other by using this simple CSS:

float: left;

without this CSS, items will line up vertically downward like traditional bullets (<UL> or <OL>).

After that, how do we control the event without using onmouseover event checker? We use this li:hover ul and li.over ul in CSS.

Basically, very simple. It's just a matter of manipulating the display parameter in CSS. When display: block, it is similar to asking the browser to SHOW; whereas, display: none is to ask the browser to HIDE. It's similar to Javascript's hidden and visible function.

Anyway, another sample is required to make this demo easier to under: making a "drop-right" modified from these codes. Stay tuned! (Update: Cannot be done, need to work around as in the coming example)




Note: Firefox needs this to hide the bullets: list-style: none;
Note2: In order for IE to work properly using these codes, you need to declare the doctype as:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

No comments:

Post a Comment