free-tech

How to make a hoverable dropdown CSS ?


What is Dropdown ?

a dropdown is a list of choices that appears on a computer screen when a person clicks on the menu's title.

How to create a hoverable dropdown:

1 - let's create the HTML:

<html>
<head>
</head>
<body>
<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#">Security</a>
    <a href="#">Web</a>
    <a href="#">Mobile</a>
    <a href="#">Databases</a>
  </div>
</div>
</body>
</html>

in this example we used a button to open the dropdown we can use any element for example <button>, <a> or <p> element. also we used a div container to to create the dropdown menu and add the dropdown links inside it. after that we wrap  the button with a div in order to position the dropdown menu with css

2 - let's add the css :

<style>
  /* Dropdown Button */
  .dropbtn {
    background-color: #0425aa;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
  }

  /* The container <div> - needed to position the dropdown content */
  .dropdown {
    position: relative;
    display: inline-block;
  }

  /* Dropdown Content (Hidden by Default) */
  .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
  }

  /* Links inside the dropdown */
  .dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
  }

  /* Change color of dropdown links on hover */
  .dropdown-content a:hover {background-color: #ddd;}

  /* Show the dropdown menu on hover */
  .dropdown:hover .dropdown-content {display: block;}

  /* Change the background color of the dropdown button when the dropdown content is shown */
  .dropdown:hover .dropbtn {background-color: #8e813e;}
</style>

- Put the style element inside  the head element of your html page.
- We added some css attributes (background-color, color, padding ...) to the class .dropbtn in order to style the button.
- The .dropdown-content class holds the actual dropdown menu. It is hidden by default, and will be displayed on hover.
- instead of using border we used box-shadow. to make it looks like a card.
- We used :hover selector to show the dropdown menu when the mouse moves over it.