How to create a drop-down menu with CSS

0 Shares
0
0
0
0

Introduction

Create a drop-down menu that appears when the user hovers the mouse over an element.

Step 1) Add HTML:

<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
Example explained.

Use any element to open a drop-down menu, e.g. an element <button>, <a> Or <p>.

From a container element (such as <div>) to create a drop-down menu and add drop-down links inside it.

An element <div> around the button and <div> Wrap so that the dropdown menu is positioned correctly with CSS.

Step 2) Add CSS:

/* Dropdown Button */
.dropbtn {
background-color: #04AA6D;
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: #3e8e41;}
Example explained

We have styled the slider button with background color, padding, etc.

The .dropdown class uses position:relative when it is necessary to position the dropdown content directly below the dropdown button (using position:absolute).

The .dropdown-content class holds the actual dropdown menu. It is hidden by default and is displayed in float mode (see below). Note that the minimum width is set to 160px. Feel free to change this. Tip: If you want the width of the dropdown content to be the same as the dropdown button, set the width to 100% (and overflow: auto to enable scrolling on small screens).

Instead of using a border, we've used the box-shadow property to make the dropdown menu look like a "card." We're also using z-index to position the dropdown in front of other elements.

The :hover selector is used to show the drop-down menu when the user hovers the mouse over the drop-down button.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like