position: sticky in CSS

Hero image for Position: sticky in CSS. Image by Hal Gatewood.
Hero image for 'Position: sticky in CSS.' Image by Hal Gatewood.

position: sticky seems to be one of those CSS properties that replace functionality that used to be typically handled through JavaScript. Allowing for elements to dynamically switch their positioning between relative and fixed based on where the viewport is in the document, position: sticky seems like a bit of a dream property. So let's take a look at it and figure out if there are any potential cons.


How does position:sticky work?

To see sticky positioning in action, let's set up a basic example:

HTML

<body>  <div className='sticky-parent'>    <p>Not Sticky</p>    <div className='sticky-child'>      <p>Sticky</p>    </div>  </div></body>

CSS

body {  height: 4000px;  padding: 0;  margin: 0;}p {  margin: 0;}.sticky-parent {  position: relative;  height: 100%;  display: block;  background: red;  height: 2000px;}.sticky-child {  position: sticky;  top: 0;}

You can check out a fairly rudimentary CodePen implementation of this here.

As we can see from this, there are a couple of things to bear in mind when working with sticky elements. For starters, we need a parent element to set out the containing wrap for any sticky element. This sets out the "end" point for the fixed positioning (in the code above, the sticky div stops being sticky about halfway down the page, where the parent container ends).

You will also need to set an "offset" parameter, like top. You can also set a bottom, left, or right value. This doesn't actually affect the initial positioning of the element at all, but it tells the browser when this element needs to become fixed. The top parameter determines how far from the top of the viewport the element needs to be before it is set to fixed, and how far away from the top of the viewport it stays when the element has become fixed.

You'll also need to ensure that the parent element has a compatible overflow property. You can't use hidden, scroll (or auto in Safari) as the value for the overflow, overflowx or overflowy properties on the parent element.


Compatibility and Support

Thankfully, the position: sticky property actually enjoys pretty widespread support! You can use it in Edge, Chrome, Firefox, Opera, and Safari (starting from versions released in late 2021 to mid2022). It also is fairly wellsupported for mobile browsers.


The Wrap‑Up

A very handy property, position: sticky seems to be one of the bettersupported CSS properties that offers some more complex and dynamic options for your elements without the use of JavaScript. It's an exciting view into the future of CSS, potentially becoming more and more mixed with the more traditional JavaScript areas of development.


Categories:

  1. Adaptive Development
  2. CSS
  3. Front‑End Development
  4. Responsive Development