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>
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>
Few points to note:
- This approach does not work on mobile and there is no hover concept in mobile
- To watch hover style for debugging purpose, you can use Google Chrome developer tools to toggle hover event. Here is how it looks: