How to create: Dropdown menu
- Previous page Sub navigation menu
- Next page Super menu
Learn how to create a dropdown menu using CSS.
Dropdown menu
A dropdown menu is a toggleable menu that allows users to select a value from a predefined list:
Create a hoverable dropdown menu
Create a dropdown menu that appears when the user moves the mouse over the element.
Step 1 - Add HTML:
<div class="dropup"> <button class="dropbtn">Dropup</button> <div class="dropup-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div>
Example explanation:
You can use any element to open the dropdown menu, such as <button>, <a>, or <p> elements.
Use a container element (such as <div>) to create a dropdown menu and add dropdown links to it.
Use the <div> element to wrap the button and <div> together, so that the CSS can position the dropdown menu correctly.
Step 2 - Add CSS:
/* Dropdown button */ .dropbtn { background-color: #3498DB; color: white; padding: 16px; font-size: 16px; border: none; } /* Container <div> - used for positioning the pull-down menu content elements required */ .dropup { position: relative; display: inline-block; } /* Pull-down menu content (hidden by default) */ .dropup-content { display: none; position: absolute; bottom: 50px; background-color: #f1f1f1; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } /* Links in the dropdown menu */ .dropup-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } /* Change the color of the dropdown link when the mouse hovers */ .dropup-content a:hover {background-color: #ddd} /* Display the pull-down menu when the mouse hovers */ .dropup:hover .dropup-content { display: block; } /* Change the background color of the pull-down button when the pull-down menu content is displayed */ .dropup:hover .dropbtn { background-color: #2980B9; }
Example explanation:
We set styles such as background color, padding, etc. for the pull-down button.
.dropup
class to use position: relative
, when we want to place the pull-down menu content above the pull-down button (using position: absolute
)), which is necessary.
.dropup-content
class contains the actual pull-down menu. It is hidden by default and will be displayed when the mouse hovers over it (see below). Note that the minimum width is set to 160px. You can change this value as needed. Tip: If you want the width of the pull-down menu content to be the same as the pull-down button, you can set the width to 100% (and use overflow: auto
to enable scrolling).
We did not use borders but instead used box-shadow
property to make the pull-down menu look like a 'card'. We also use z-index
Place the pull-down menu in front of other elements.
:hover
The selector is used to display the dropdown menu when the user hovers over the pull-down button.
- Previous page Sub navigation menu
- Next page Super menu