Bootstrap, keep div fixed after scrolling to it
Bootstrap 4.0+ update
Please note that the affix
is removed from bootstrap as mentioned here. As of 2018, I also suggest you to avoid jQuery and move to angular, react or vue for better coding practices.
To make that happen now from bootstrap 4.0, you need to use the sticky-top
class.
Sample code:
<div class="card sticky-top">
...Something
</div>
And it looks like this:
If you want some padding & margin, you can set that up or add another div with the same class on top of it, etc. Be creative :)
As per Bootstrap docs, you must write the .affix
, .affix-top
and .affix-bottom
styles yourself.
.affix {
top:50px;
position:fixed;
}
To define where the affix begins, you can use an data-offset-*
attribute on the element:
<div data-spy="affix" data-offset-top="50">
Edit: I made a quick JSFiddle to better illustrate the usage.
with bootstrap and jQuery
$(document).ready(function(){
// bind and scroll header div
$(window).bind('resize', function(e){
$(".affix").css('width',$(".container-fluid" ).width());
});
$(window).on("scroll", function() {
$(".affix").css('width',$(".container-fluid" ).width());
});
});
.affix {
top:50px;
position: fixed;
width: 100%;
background-color:white;
z-index:777;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class='container-fluid'>
<div data-spy="affix" data-offset-top="50">
<div class="header_for_fix" >
<div>First</div>
<div>Second</div>
<div>Third</div>
</div>
</div>
</div>