css dropdown menu

April 18, 2019

hosein

Tutorials

css only animated dropdown

We should always develop smooth and fast websites and web apps, while js can help us with creating animations, js animations sometimes lag on low end mobile devices and it’s always better to use css instead of javascript whenever possible.

In today’s quick tutorial we’ll create a a dropdown menu only with css.

what we will create will look like this pen:

See the Pen css only animated drop down by Hosein Hamzenejad (@envoy47) on CodePen.0

1-  html code


so we imagine the dropdowns are li items in ul tags, just like most navigating menus. div .dropdown will reveal when we hover li. and .drop-link are the items of the dropdown menu.

<li>
  hover me <i class='down'></i>
  <div class='dropdown'>
    <a class='drop-link' href='#'>Link1</a>
    <a class='drop-link' href='#'>Link2</a>
    <a class='drop-link' href='#'>Link3</a>
    <a class='drop-link' href='#'>Link4</a>
    <a class='drop-link' href='#'>Link5</a>
  </div>
</li>

2-  style dropdown button and add hover event

li{
  padding:15px;
  margin: 15px auto;
  width:100px;
  border:none;
  background:#9b59b6;
  color:#fff;
  border-radius:7px;
  font-size:14px;
  transition:all 0.3s ease;
  text-align:center;
  list-style-type:none;
  font-family:sans-serif;
}

li:hover{
  background:#a06fb4;
  cursor:pointer;
}

/* arrow down */
i {
  border: solid white;
  margin-left:5px;
  border-width: 0 3px 3px 0;
  display: inline-block;
  padding: 3px;
}

.down {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
}


3-  style dropdown content

now add some styles to dropdown div and links inside it:

.dropdown{
  z-index:-1;
  position:absolute;
  visibility: hidden;
  opacity:0;
  color:black;
  background:#e1e6ea;
  width:200px;
  margin-top:20px;
  margin-left:-15px;
  transition:all 0.3s ease;
  border-radius:0px 0px 7px 7px;
  transform:translateY(15px);
  cursor: default;
}

.drop-link{
  display:block;
  text-align:left;
  text-decoration:none;
  font-size:15px;
  padding:10px 15px;
  transition:all 0.3s ease;
  color:#000;
}

.drop-link:hover{
  font-size:18px;
  background: #d4dade;
}

.drop-link:last-of-type{
  border-radius:0px 0px 7px 7px;
}

4- reveal dropdown on li hover

change .dropdown’s  visibility to visible and z-index to 1 to reveal it on parent hover:

li:hover > .dropdown{
  z-index:1;
  opacity:1;
  visibility: visible;
  transform:translateY(0px);
}