DEV Community

Cover image for How to create a simple CSS only dropdown
Anton
Anton

Posted on • Originally published at Medium

How to create a simple CSS only dropdown

This is a small CSS tutorial I decided to write this morning. Maybe later I should do more.

Today's topic gonna be CSS based dropdown menu. The code itself was written from scratch. It took me around 30 minutes. The only external code was used is CSS reset.

I am using Pug to write quick HTML and SCSS.

The first thing is to create a dropdown container div.

Then put inside a button. It will serve as a trigger. Then we put inside an unordered list with a few items.

.dropdown
 button.trigger-btn Hover me
  ul.dropdown__items
   li.dropdown__item Menu item 1
   li.dropdown__item Menu item 2
   li.dropdown__item Menu item 3
   li.dropdown__item Menu item 4
Enter fullscreen mode Exit fullscreen mode

Then we add padding, background color, etc.

For color selection, Material colors were used. There you can quickly choose some nice-looking colors.

Shadows for the dropdown were generated with a help of a CSS generator.

We finished with styles and HTML. Now, how actually does the magic works?

In order to have a dropdown appear on mouse-over we need to set :hover pseudo-class. When the .dropdown container is mouse-over.dropdown__items element becomes visible by adding display:block CSS rule.

Check out the code example to understand better how it works:

Top comments (1)

Collapse
 
antmik profile image
Anton

Thanks for the feedback. Yes, you are right it's not accessible. In production project I'd rather use JS based dropdown what will allow adaptability to the side of the screen