How to create a dropdown with pure CSS

In HTML, the dropdown is created using the select and option tags. However, it is also possible to create a dropdown using pure CSS. This is achieved by using the CSS property called “display: none” to hide a list of options and then using the “hover” selector to display it when the user hovers over the dropdown button.

Here is the syntax for creating a dropdown with pure CSS:

“`html

“`

In this example, we have a div with a class of “dropdown” that contains a button which acts as the dropdown button. We also have a ul with a class of “dropdown-menu” that contains a list of options.

To hide the options by default, we can use the following CSS:

“`css
.dropdown-menu {
display: none;
}
“`

Then, to display the options when the user hovers over the dropdown button, we can use the following CSS:

“`css
.dropdown:hover .dropdown-menu {
display: block;
}
“`

This will display the options only when the user hovers over the dropdown button. To make it so that the options stay displayed when the user hovers over them, we can modify the CSS like so:

“`css
.dropdown:hover .dropdown-menu,
.dropdown-menu:hover {
display: block;
}
“`

This will keep the options displayed as long as the user is hovering over the dropdown button or any of the options.

Here is a full example of a dropdown with pure CSS:

“`html

.dropdown-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
padding: 0;
margin: 0;
list-style: none;
background-color: #fff;
border: solid 1px #ccc;
}

.dropdown-menu li a {
display: block;
padding: .5em 1em;
color: #333;
text-decoration: none;
}

.dropdown:hover .dropdown-menu,
.dropdown-menu:hover {
display: block;
}

“`

This will create a dropdown button with three options that appear when the user hovers over it.

Here is a link to a tutorial on creating a dropdown with pure CSS:

https://www.w3schools.com/howto/howto_css_dropdown.asp

  Written by: Michael from Beginnrtuts.com     20-06-2023     Written in: CSS tutorials

Leave a Reply