There’s a new value in town for the CSS position property: sticky
. It allows us to make elements stick when the scroll reaches a certain point. An element with position: sticky
will behave like a relatively-positioned element until it reaches a specified point and then starts behaving like a statically-positioned element. In this post we’ll create a simple example to illustrate.
We’ll have a div
container that will be a flex container and then 4 additional div
elements that will be the flex items. Note we don’t have to use flexbox at all for position: sticky to work, here it’s just that flexbox happens to work great for our example.
Check our flexbox primer if you'd like a refresher on the different flexbox properties and values.
Here’s the simple markup:
<div class="container"> <div class="item pirate"> <img src="/images/pirate.svg" width="100" alt="Item 1"> </div> <div class="item police"> <img src="/images/police.svg" width="100" alt="Item 2"> </div> <div class="item cowboy"> <img src="/images/cowboy.svg" width="100" alt="Item 3"> </div> <div class="item doctor"> <img src="/images/doctor.svg" width="100" alt="Item 4"> </div> </div>
And now our styles, with the important rules highlighted:
.container { display: flex; justify-content: space-around; align-items: flex-start; border: 2px dashed rgba(114, 186, 94, 0.35); height: 400px; background: rgba(114, 186, 94, 0.05); } .pirate { position: -webkit-sticky; position: sticky; top: 4rem; } .police { position: -webkit-sticky; position: sticky; top: 0; } .doctor { position: -webkit-sticky; position: sticky; bottom: 1rem; align-self: flex-end; }
And here’s the result. Try scrolling the page up and down to notice what happens: 😜
Pretty neat hey! Such effect used to only be achievable using some JavaScript and registering a scroll handler.
Here are a few additional things to note:
- With our example, the
align-items: flex-start
rule on the flex container is important because otherwise flex items default to a value of stretch
where the elements would take the whole height of the container, cancelling the sticky effect. - We need to make use of the
-webkit-sticky
vendor prefix for it to work in Safari. - It’s important that you set a point for the element to become sticky using either of the
top
, bottom
, left
or right
properties, depending on which direction the user will scroll. - Notice how sticky-positioned elements are only sticky within their parent element.
Have a look at our resources page for a real life example of how position: sticky
can be used to accomplish a nice effect with nothing but CSS.
Browser Support
Can I Use css-sticky? Data on support for the css-sticky feature across the major browsers from caniuse.com.