Bootstrap 4 Navbar Toggle Without Javascript/jQuery

May 3, 2019

Navbar Html

  • Replace <button class="navbar-toggler" ... with <label for="lua-navbar-toggler" ... + <input type="checkbox" id="lua-navbar-toggler" class="d-none" />.
  • We use a hidden checkbox so that we can utilize CSS :checked selector coupled with + (immediate adjacent selector) or ~ (all adjacent selector) to change .collapse into visible.
  • We use <label> to handle checkbox clicking, as <input type="checkbox"> is contraint by its size and UI.
<nav class="navbar navbar-expand-xl navbar-light bg-light">  <div class="container">    <a class="navbar-brand" href="/">      <img src="/img/logo-icon.png" width="36" height="36" class="d-inline-block align-middle" alt="">      Lua Software Code    </a>    <!--    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#lua-navbar-content" aria-controls="lua-navbar-content" aria-expanded="false" aria-label="Toggle navigation">      <span class="navbar-toggler-icon"></span>    </button>    -->    <input type="checkbox" id="lua-navbar-toggler" class="d-none" />    <label for="lua-navbar-toggler" class="navbar-toggler" data-toggle="collapse" data-target="#lua-navbar-content" aria-controls="lua-navbar-content" aria-expanded="false" aria-label="Toggle navigation">      <span class="navbar-toggler-icon"></span>    </label>    <div class="collapse navbar-collapse" id="lua-navbar-content">      <ul class="navbar-nav">        <li class="nav-item ">            <a class="nav-link" href="/tutorials/">              Tutorials            </a>        </li>        <li class="nav-item ">            <a class="nav-link" href="/about/">              About            </a>        </li>      </ul>    </div>  </div></nav>

CSS - make all adjacent .collapse visible when checkbox is checked

#lua-navbar-toggler:checked ~ .collapse {    display:block;}

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.