Search code examples
htmlcssbootstrap-5

How to show scrollbar in sidebar


I am designing a view ads page. I am not super savvy about bootstrap. I want to have a scrollbar in the filters to browse all the contents. The filter should stay fixed while the user browse ads in the main section.

<head>
<link
rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"/>
</head>
<body>

<div class="container-fluid">
  <div class="row">
    <div
      class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse"
      id="sidebar"
    >
      <form class="needs-validation" novalidate>
        <div class="mb-3">
          <label for="view">View</label>
          <select class="form-control" id="view" name="view">
            <option value="gallery">Gallery</option>
            <option value="list">List</option>
          </select>
        </div>
        <div class="mb-3">
          <label for="sort">Sort</label>
          <select class="form-control" id="sort" name="sort" value="">
            <option value="newest">Newest</option>
            <option value="oldest">Oldest</option>
          </select>
        </div>
        <div class="mb-3">
          <input
            type="checkbox"
            class="form-check-input"
            id="has_images"
            name="has_images"
          />
          <label class="form-check-label" for="has_images">Has Images</label>
        </div>
         
        <div class="d-flex justify-content-between">
          <button type="submit" class="btn btn-outline-primary">Reset</button>
          <button type="submit" class="btn btn-primary">Apply</button>
        </div>
      </form>
    </div>
    <main class="col-md-9 col-lg-10 px-md-4">
      <div class="d-flex justify-content-end pt-3 pb-2 mb-3 border-bottom">
        <button
          class="btn btn-secondary d-md-none"
          type="button"
          data-toggle="collapse"
          data-target="#sidebar"
        >
          Toggle Filters
        </button>
      </div>
    </main>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>
</html>

As the picture shows: filter with scrollbar

I tried adding "position=fixed" to the sidebar, but the main ads overlapped with the sidebar.


Solution

  • This should work.

    .sidebar {
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      width: 16.66667%;
      overflow-y: auto; 
      padding-top: 1rem; 
    }
    /* Make sure the main content starts after the sidebar */
    main {
      margin-left: 16.66667%; /* Same width as the sidebar */
    }