Search code examples
htmlcssdrop-down-menudropdown

Dropdown Menu with pure CSS and HTML


I have below CSS for a dropdown menu:

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  right: 0;
  top: 30px;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;

  button, a {
    border-bottom: 1px solid #e7e7e7;
    border-radius: unset;
    text-align: left;
    display: inline-block;
    width: 100%!important;

    .icon {
      margin-right: 15px;
      top: 0.13em;
    }

    &:hover {
      background-color: #e7e7e7 !important;
    }

    &:active {
      background-color: #c7c7c7 !important;
    }
  }
}

.dropdown:hover .dropdown-content {
  display: block;
}

And below markup:

                <div class="dropdown">
                  <button class="material-icon-button">
                    <i class="icon icon-more_vert"></i>
                  </button>
                  <div class="dropdown-content" style="width: 295px;">
                    <button class="material-button">
                      <i class="icon icon-undo"></i>
                      <span>Button 1</span>
                    </button>
                    <button class="material-button">
                      <i class="icon icon-add_alert"></i>
                      Button 2
                    </button>
                  </div>
                </div>

This works fine and shows menu on mouseover.

What I am trying to achieve is that, instead of mouseover, the dropdown is shown when the user actually clicks the button.

I have tried:

.dropdown:active .dropdown-content {
  display: block;
}

But It doesn't seem to work, it show the menu on click but hides immediately.

I was wondering if this could be done without JavaScript and with pure css? if so, can someone please guide on this.

Thanks


Solution

  • There is a way to handle clicks with pure CSS. It's not the best way (because that's not what CSS is made for) but it should work. Basically you'll have to use a checkbox with a label and style according to the state of the checkbox.
    Here is an example: https://css-tricks.com/the-checkbox-hack/