How to create: fixed header when scrolling
- Previous Page Gradient Background Scroll
- Next Page Header Shrinks on Scroll
Learn how to use CSS and JavaScript to create a fixed/sticky header when scrolling.
Create a fixed header when scrolling
Step 1 - Add HTML:
<div class="header" id="myHeader"> <h2>My Header</h2> </div>
Step 2 - Add CSS:
Set the style of the page header; add position: sticky and top: 0 to keep the header fixed when scrolling to the top..header { position: sticky; top: 0; padding: 10px 16px; background: #555; color: #f1f1f1; }
element is set to position: sticky;
After that, its position will be determined by the user's scroll position.
Sticky elements switch between relative and fixed positioning based on the scroll position. Before reaching the given offset position within the viewport, it maintains relative positioning; after reaching it, it will 'stick' at that position (like position: fixed
same).
Note:To make sticky positioning work, you must at least specify top
,right
,bottom
or left
of one.
Related Pages
Tutorial:CSS position
- Previous Page Gradient Background Scroll
- Next Page Header Shrinks on Scroll