I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.
Can I do this using just css and html or do i need jquery too?
The chosen solution did not fit well in my page. So this is a more advanced version that works with bootstrap.
The javascript
var stickyOffset = $('.sticky-header').offset().top;
$(window).scroll(function () {
var sticky = $('.sticky-header'),
scroll = $(window).scrollTop(),
header = $('.fixed-header-background');
sticky.each(function() {
var left = $(this).offset().left;
$(this).data('left', left);//I store the left offset
});
if (scroll >= stickyOffset) {
sticky.addClass('fixed');
header.css('display', 'block');
sticky.each(function() {
$(this).css('left', $(this).data('left'));//I set the left offset
});
} else {
sticky.removeClass('fixed');
header.css('display', 'none');
sticky.each(function () {
$(this).css('left', '');//I remove the left offset
});
}
});
The CSS
.fixed-header-background {
display: none;
position: fixed;
top: 50px;
width: 100%;
height: 30px;
background-color: #fff;
z-index: 5;
border-bottom-style: solid;
border-bottom-color: #dedede;
border-bottom-width: 2px;
}
.fixed{
position: fixed;
top: 52px;
z-index: 6;
}
And the HTML
My header 1
My header 2
[....]