简体   繁体   中英

How to auto collapse Bootstrap 4 Sidebar for smaller screens?

This is my current code, I've managed to hide the sidebar with the collapse button, but I want it to only collapse for small devices, like the bootstrap navbar does.

 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="container-fluid"> <div class="row"> <div class="col-md-3 px-1 bg-light" id="sidebar"> <div class="py-2 sticky-top flex-grow-1"> <div class="nav flex-sm-column"> <h2 class="text-center">PROFILE</h2> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".collapse" aria-expanded="true" aria-controls="collapse">Toggle both elements</button> <div class="collapse navbar-collapse"> <a href="" class="nav-link">LINK</a> <a href="" class="nav-link">LINK</a> <a href="" class="nav-link">LINK</a> </div> </div> </div> </div> <div class="col-sm-9" id="main"> ***PAGE DATA </div> </div> </div> </div> 

You could use a media query to do this:

@media (max-width: 568px) {
  #sidebar {
    display: none;
  }
}

I think if you use this it will help solve your problem. You can learn more from here W3SCHOOLS

   @media only screen and (min-width: 320px) and (max-width: 768px) {
  .nav {
    width:100%;
  }
  .nav-link {
    width:100%;
    float:none;
  }
}

This is what you are looking for. What the others have written above will work but it is harder than just using bootstrap classed.

https://getbootstrap.com/docs/4.1/utilities/display/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM