Malcolm Brown
Malcolm Brown

Reputation: 23

CSS dropdown menu with checkbox hack

I am no expert in CSS, and I can't for the life of me get the checked option to display a div. In my head this should work, but it doesn't. Any help would be greatly appreciated. I think the problem is with this line of code.

.mobile-trigger:checked ~ .drop {
display: block;
}

Example

Upvotes: 2

Views: 824

Answers (1)

emmanuel
emmanuel

Reputation: 9615

You have to hide content by default and once input is checked display: block will show it. Please note that general sibling combinator ~ "separates two selectors and matches the second element only if it is preceded by the first, and both share a common parent" so the element that has to be shown has to be a sibling after the checkbox.

.drop {
  display: none;
}
.mobile-trigger:checked ~ .drop {
  display: block;
}
<input type="checkbox" class="mobile-trigger">
<div class="drop">test</div>

Reference: MDN - General sibling selectors

Upvotes: 2

Related Questions