position: fixed places an element relative to the browser window (the viewport). It stays there as the page scrolls.
.back-to-top {
position: fixed;
right: 20px;
bottom: 20px;
}
This is how floating “back to top” buttons, cookie banners and chat bubbles work.
<style>
.fixed-bar { position: fixed; top: 0; left: 0; right: 0; background: #1a5276; color: #fff; padding: 8px 12px; font-size: 14px; }
body { padding-top: 40px; }
</style>
<div class="fixed-bar">I stay at the top. Scroll the Result panel.</div>
<p>Scroll down in this panel.</p>
<div style="height: 400px; background: linear-gradient(#fff, #d0e8f2)"></div>
<p>More content below.</p>
Scroll inside the Result panel: the blue bar stays put. Note the padding-top on the body. Since a fixed element leaves the flow, the content would otherwise slide underneath it.
Remember to leave room
A fixed header covers the content below it. Add a padding-top or margin-top equal to its height.
Fixed headers and in-page links
If a link jumps to #section and your fixed header covers the top of the section, add scroll-margin-top to the target: section { scroll-margin-top: 80px; }.
When fixed does not behave
- A
transform,filterorperspectiveon a parent makes it the reference instead of the window, which breaks the pinning. - On small screens, a big fixed header eats a lot of the visible area. Keep them slim.