How to keep the header static, always on top while scrolling?
position: sticky;
In modern, supported browsers, you can simply do that in CSS with -
header {
position: sticky;
top: 0;
z-index: 999;
}
In most case, it is better than using position: fixed
, since position: fixed
takes the element out of the regular flow of elements.
Note:
- The HTML structure is important while using
position: sticky
, since it makes the element sticky relative to the parent. And the sticky positioning might not work with a single element made sticky within a parent. - The parent of the element made sticky should not have the
overflow
property set Eg: if parent hasoverflow: auto
oroverflow: hidden
, then sticky positioning might not work - Giving at least one of the
top
,bottom
,left
,right
is important because it makes the element sticky in relation to some position.
Run the snippet below to check a sample implementation.
main {
padding: 0;
}
header {
position: sticky;
top:0;
padding:40px;
background: lightblue;
text-align: center;
}
content > div {
height: 50px;
}
<main>
<header>
This is my header
</header>
<content>
<div>Some content 1</div>
<div>Some content 2</div>
<div>Some content 3</div>
<div>Some content 4</div>
<div>Some content 5</div>
<div>Some content 6</div>
<div>Some content 7</div>
<div>Some content 8</div>
</content>
</main>
Note: This answer dates from 2010. Consider position: sticky
in 2021, as mentioned in another answer.
Use position: fixed
on the div
that contains your header, with something like
#header {
position: fixed;
}
#content {
margin-top: 100px;
}
In this example, when #content
starts off 100px below #header
, but as the user scrolls, #header
stays in place. Of course it goes without saying that you'll want to make sure #header
has a background so that its content will actually be visible when the two div
s overlap. Have a look at the position
property here: http://reference.sitepoint.com/css/position