Web4College

How to show/hide a menu bar on mouse hover

CSS :hover pseudo-class allows the user to change the CSS properties on mouse hover. For example, We have a different set of properties for an element. This set may be changed on a mouse hover. We can also change the value of display property on mouse hover. This effect will help us in designing the drop down menu that displays or hides a menu on mouse hover.

You must have knowledge about the display, position properties. We may have many cases where you'll use different types of selectors to change the behavior of an element on a mouse hover.

See the following unordered list containing another unordered list as the child of a list item. Here we have described how to show/hide a menu bar. Learn how to make a menu bar.

Example
Try it
<div id="ourMenu">
 <ul>
  <li>One</li>
  <li>Two</li>
  <li>Three
	<ul>
	 <li>3.1</li>
	 <li>3.2</li>
	 <li>3.3</li>
	</ul>
   </li>
  <li>Four</li>
 </ul>
</div>

Now, we'll hide the sub menu with display:none; property. And we'll show this menu bar on mouse hover with display:block; property.

Example
Try it
<style>
#ourMenu ul li ul{
display:none;	
}

#ourMenu ul li:hover ul{
display:block;	
}
</style>

#ourMenu ul li ul means we have an unordered list that contains another unordered list as the child of list item. And we have set the display:none; property for this unordered list.

#ourMenu ul li:hover ul means that the display:block; property is applied to the child ul when a user hovers the mouse over a list item (li) whick is also a child of some other list item.


Now, you may also have an icon that you hover on to show/hide a menu bar. In this case, we use CSS '+' combinator to display the element very next to the current icon.

Example
Try it
<div id="myIcon"></div>
<div class="myMenu">
 <ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
 </ul>
</div>

Now, we'll show the ordered list when a user hovers the mouse over the #myIcon div. See the CSS given below.

Example
Try it
<style>
div.myMenu{
display:none;	
}

#myIcon:hover+div.myMenu{
display:block;	
}
</style>