Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 4 fixed top nav and fixed sidebar

This is a great example of how to create a navbar with a sidebar. Can anyone modify the code so that the top nav is top-fixed and the sidebar fixed/static with only the main page content scrolling? I can make the nav the nav top-fixed by assigning the class="fixed-top" to the nav, but I can't figure out how to make the sidebar fixed so that it remains in the same spot instead of scrolling up with the main page content. Applying class="sticky-top" to the sidebar doesn't seem to work.

<nav class="navbar navbar-expand-md navbar-dark bg-primary fixed-top">
    ..
</nav>
<div class="row">
    <div id="sidebar-container" class="sidebar-expanded d-none d-md-block">
        <ul class="list-group sticky-top">
            <li>Menu item..</li>
            <li>Menu item..</li>
        </ul>
    </div>
    <div class="col">
        <!-- MAIN -->
    </div>
</div>

https://www.codeply.com/go/LFd2SEMECH

like image 531
user3691644 Avatar asked Apr 04 '18 01:04

user3691644


People also ask

How can make navbar fixed top in bootstrap 4?

Use the . sticky-top class to make the navbar fixed/stay at the top of the page when you scroll past it.

How do I keep my navbar fixed on top?

To create a fixed top menu, use position:fixed and top:0 .

Which Bootstrap CSS class will you use to hold the navbar at the top of the page?

Use the . navbar-text class to vertical align any elements inside the navbar that are not links (ensures proper padding and text color).


2 Answers

The sticky-top is working, but it doesn't appear to be working for two reasons...

  1. There isn't enough content in the main content area to scroll
  2. It's positioned at top:0 so it hides behind the fixed navbar

Add CSS to offset the top of the sidebar (the same as height of fixed navbar).

.sticky-offset {
    top: 56px;
}

<ul class="list-group sticky-top sticky-offset">..(sidebar)..</div>

And, then add enough content (or height) in the main area so that scrolling is necessary...

Working Demo: https://www.codeply.com/go/7XYosZ7VH5

<nav class="navbar navbar-expand-md navbar-dark bg-primary fixed-top">
    ..
</nav>
<div class="row">
    <div id="sidebar-container" class="sidebar-expanded col-2 d-none d-md-block">
        <ul class="list-group sticky-top sticky-offset">
            <li>Menu item..</li>
            <li>Menu item..</li>
        </ul>
    </div>
    <div class="col">
        <!-- MAIN -->
    </div>
</div>
like image 135
Zim Avatar answered Sep 21 '22 20:09

Zim


There's a relatively new CSS position property called sticky.

position: sticky;
top: 4em;

See how this works, what happens when you scroll to the end of the parent element. Leave height at auto. Reference - https://developer.mozilla.org/en-US/docs/Web/CSS/position

like image 24
mate.gvo Avatar answered Sep 21 '22 20:09

mate.gvo