2

I am creating a side navigation bar using CSS only. I was able to trigger dropdown menus using checkbox triggers:

[type="checkbox"] {
    display: none;
    &:checked ~ div
    {
        display: block;
    }
}

HTML Structure:

<ul>
    <li>
        <input type="checkbox" id="chk1">
        <label for="chk1">Dropdown 1</label>
        <div class="dropnav">
           .. list of sub menu
        </div>
    </li>
    <li>
        <input type="checkbox" id="chk2">
        <label for="chk2">Dropdown 1</label>
        <div class="dropnav">
           .. list of sub menu
        </div>
    </li>
    <li>
        <input type="checkbox" id="chk3">
        <label for="chk3">Dropdown 1</label>
        <div class="dropnav">
           .. list of sub menu
        </div>
    </li>
</ul>

So as you can see when the checkbox is 'checked' the next sibling div element will be display: block to show the dropdown menus, and it's working. However I have multiple dropdown menus and I would like close other dropdown menus when one of them was open. For example if I trigger the 'chk1' it will open its sibling 'dropnav' menu then the other 'dropnav' will be closed (display: none). Is this possible for a CSS only solution?

vedsil
  • 137
  • 18
saionachi
  • 397
  • 1
  • 5
  • 21

1 Answers1

2

Use type radio with the same names instead of checkboxes:

[type="radio"] {
  display: none;
}

.dropnav {
  display: none;
}

[type="radio"]:checked~div {
  display: block;
}
<ul>
  <li>
    <input type="radio" name="c" id="chk1">
    <label for="chk1">Dropdown 1</label>
    <div class="dropnav">
      .. list of sub menu
    </div>
  </li>
  <li>
    <input type="radio" name="c" id="chk2">
    <label for="chk2">Dropdown 1</label>
    <div class="dropnav">
      .. list of sub menu
    </div>
  </li>
  <li>
    <input type="radio" name="c" id="chk3">
    <label for="chk3">Dropdown 1</label>
    <div class="dropnav">
      .. list of sub menu
    </div>
  </li>
</ul>
Stephen P
  • 14,422
  • 2
  • 43
  • 67
Nasim B. D
  • 161
  • 1
  • 6