htmltwitter-bootstrapcssaffix

How to fix some divs on top while scrolling using bootstrap?


I am using bootstrap in Angular 2 project and I want to freeze couple of divs(with ids as filters and categories in the code) on top always, while user scrolls down the page.

This is the code that I have in jsfiddle here

Code Snippet:

    <nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>

        </div>
        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">

                <li routerLinkActive="active"><a routerLink="/overview">Overview</a></li>
                <li routerLinkActive="active"><a routerLink="/insights">Insights</a></li>
            </ul>






        </div>
        <!--/.nav-collapse -->


    </div>
</nav>


<div id="filters" class="container-fluid" style="margin-top: 60px" >

    <div class="row">
      <div class="col-md-2 col-sm-4">
        <button>Filter 1</button>
      </div>
       <div class="col-md-2 col-sm-4">
       <button>Filter 2</button>
       </div> 
    </div>
</div>

<div id="categories" class="container-fluid"  >
    <div class="row">
         <ul class="nav navbar-nav">

                <li><a routerLink="#">Sub Category 1</a></li>
                <li><a routerLink="#">Sub Category 2</a></li>
            </ul>

    </div>

    <div class="row">

        <div class="col-md-6 col-sm-12 col-xs-12">
            <div style="background: blue; height: 800px;">
              Trend Chart
            </div>
        </div>
        <div class="col-md-6 col-sm-12 col-xs-12">
            <div style="background: green; height: 800px;">
              Bar Chart
            </div>
        </div>
    </div>



</div>

I have tried using bootstrap's 'affix', but it is breaking the scroll and the margins of 'filters' and 'categories' divs, as can be seen here

Kindly let me know if I am missing anything else that needs to be added for affix to work.


Solution

  • To achieve your goal you need to use position: fixed and z-index: 1030 CSS with your div

    Here's the jsfiddle

    Use this CSS in your div

    <div id="filters" class="container-fluid" 
    style="margin-top: 60px; position: fixed; z-index: 1030;">
    
        <div class="row">
          <div class="col-md-2 col-sm-4">
            <button>Filter 1</button>
          </div>
           <div class="col-md-2 col-sm-4">
           <button>Filter 2</button>
           </div> 
        </div>
    </div>