How to make Dropdown menu by css

Bonus: How to add arraw in the list item which has children(dropdown) menu by Jquery.

Here is the easiest way to make dropdown menus by css.

Firstly add your html markups,


<nav class="nav">
<ul class="menu">
<li><a href="">Home</a></li>
<li><a href="">about</a></li>
<li><a href="">Dropdown</a>
<ul>
<li><a href="#">item</a>
<ul>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
</ul>
</li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
</ul>
</li>
<li><a href="">feature</a></li>
<li><a href="">contact</a></li>
</ul>
</nav>

Then add the Css like below.

.nav ul li{
list-style: none;
float: left;
position: relative;
margin-left: 10px;
display:block;
}
.nav ul li a{
font-size:15px;
color:red;
text-decoration: none;
padding:10px;
display:block;
text-transform: uppercase;
}
.nav ul li a:hover{
background:#000;
color:#fff;
}
.nav ul li ul{
position:absolute;
display:none;
z-index: 333;
left:60px;
}
.nav ul li:hover > ul{
display:block;
}
.nav ul li ul li a{
font-size:12px;
display:inline-block;
width:120px;
}
.menu li a span {
display: inline-block;
width: 0;
height: 0;
margin-left: 5px;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 10px solid red;
}
.menu li ul li a span {
display: inline-block;
width: 0;
height: 0;
margin-left: 5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 10px solid red;
}

For the arraw add this Jquery code like below. And don’t forget to add the jquery file in you html file.

$(function() {
$('.menu a').each(function() {
if ( $(this).parent('li').children('ul').size() > 0 ) {
$(this).append('<span></span>');
}
});
});

That’s all.


Leave a Reply