CSS menu using css pseudo element :hover

CSS hover pseudo element can be used to create simple menu without using any Javascript. This is achieved by making menu children visible when parent element is hovered. Here are the steps to create it:

Create a menu item and its children

First lets create a menu and its children which are always visible. Here is the code:

<style type="text/css">
  .menutest {display: inline-block; background-color:lightgray;}
  .menutest ul {padding:0; margin:0}
</style>

<div class="menutest">
<a href="#">Menu</a>
<ul>
<li><a href="#">Child1</a></li>
<li><a href="#">Child1</a></li>
<li><a href="#">Child1</a></li>
</ul>
</div>
refresh

Hide menu children and show on hover

Now we can hide ul using display:none; and show it when hover occurs on menu block with class="menu"

Here is the code and how it renders:

<style type="text/css">
  .menutest {display: inline-block; background-color:lightgray;}
  .menutest ul {padding:0; margin:0}
  .menutest ul {display:none;}
  .menutest:hover ul {display:block};
</style>

<div class="menutest">
<a href="#">Menu</a>
<ul>
<li><a href="#">Child1</a></li>
<li><a href="#">Child1</a></li>
<li><a href="#">Child1</a></li>
</ul>
</div>
refresh

Few points to note:

  1. This approach does not work on mobile and there is no hover concept in mobile
  2. To watch hover style for debugging purpose, you can use Google Chrome developer tools to toggle hover event. Here is how it looks:

    chrome-developer-tools-hover-option

    chrome-developer-tools-hover-option

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments