Ask Question

How can i make an element sticky with CSS only?

In my web application, I have a banner which is displayed below the navigation of the page. I want it to be sticky, so that as soon as the user scrolls and the banner would be outside of the viewport, it is still visible and sticky to the top of the viewport.

Is there a CSS only solution I can use to achieve this?

CSSHTML

1397 views

Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

Oh yeah there is! At least the most modern browsers support the sticky value of the position property which is a solution for the exact usecase you've described.

For example if you have a DOM structure like this:

<html>
  <body>
    <nav></nav>
    <div class="banner"></div>
    <main></main>
    <footer></footer>
  </body>
</html>

If you want the .banner element to be sticky, then your CSS should look like this:

.banner {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

The top: 0; part is necessary, to tell the browser where the element should stick to. You could also set left, right or bottom if your element should stick to other areas of the viewport.

You also need to make sure that no parent element above the sticky-position element has set the overflow property to scroll, auto, or hidden. In order to make it work in safari you also need to set position: -webkit-sticky.

As already mentioned, the most modern browsers support the sticky value of the position property, but for example if you need to support Internet Explorer 11, you will need to implement a workaround with JavaScript. Here you can see a detailed report about browser support for the sticky value: https://caniuse.com/css-sticky

๐Ÿ‘
1
โค๏ธ
1