Sunday, September 28, 2014

Fixed header on scroll

Having fixed header is very user friendly to any website and these below steps will show you how to have a fixed header with minimum steps. And there is an fiddle example at the bottom of this post.

fixed navigation header on page scroll


For this example, I am creating navigation header and a table below it in a html file.

Note: Bootstrap css has been used for navigation and datatable.

 Bootstrap CDN available here :

//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css


Step 1:
  Create a html file and add simple navigation header and wrap it in a div block with a class name as 'navigation'
<ul class="nav nav-pills">
  <li class="active"><a href="#">Home</a></li>
  <li><a href="#">Profile</a></li>
  <li><a href="#">Messages</a></li>
</ul>

Step 2:
   Create a simple datatable with the below code and put it in a div with class name as 'datatable'
<table class="table table-condensed table-bordered">
       <thead>
           <tr><th>Head1</th><th>Head2</th></tr>
       </thead>
       <tbody>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
           <tr><td>Col1</td><td>Col2</td></tr>
       </tbody>
</table>

Step 3:
   Now, add custom styles to your html code either in the same file or add it as an external css file

// Style to Navigation block.
.navigation {
    padding:8px; /* Some space around navigation pills */
    position:fixed; /* IMP.This makes the div fixed and cannot to moved*/
    top:0;          /* This will set the top edge position*/
    border:1px solid green; /* I Just gave it to differentiate between table and header*/
    background:#fff; 
    width:100%;    /* Occupies 100 percent of the page width*/
}
// Style to Datatable block
.datatable {
    margin-top:60px; // Top edge margin
}


At the end of step 3, you should be able to scroll the table with header as fixed (Note: For scroll bar to appear, the height of the browser should be less than the height of the page content. In our example browsers height should be less than table's height.)

 Fiddle available for this example here : http://jsfiddle.net/94hnes36/