Have you ever been on a website where an element “sticks” to the screen and follows you as you scroll down the page? This is what we call a sticky sidebar. In this article, we are going to discuss how to create a sticky sidebar with pure CSS.
CSS Sticky Sidebar is a feature that allows web developers to create a sidebar that “sticks” to the top or bottom of the user’s screen as they scroll. This allows the sidebar to remain visible even when the user scrolls down the page, allowing them to access important information quickly and easily.
This is a web design technique to keep the sidebar on the screen even if the user has scrolled past the position where it was initially displayed.
Creating page content that sticks to the viewport as you scroll, has never been easier. Throw a position: sticky
into your CSS, you can create a sticky sidebar with pure CSS with minimal effort
Add the following CSS code to your sidebar style to make it sticky.
.sidebar{
--offset: 2rem;
flex-grow: 1;
align-self: start;
position: sticky;
position: -webkit-sticky;
top: var(--offset);
}
Some browsers like safari don’t support normal sticky, for support this in Safari we use position: -webkit-sticky
.
Position sticky alternates the position of an element between relative and fixed based on the viewer’s scroll position. A sticky element is relative to the document flow until a defined scroll position is reached, then it switches to behaving like a fixed element within its direct parent. Once, the sticky element hits the bottom of its parent, it doesn’t scroll past it.
Example of sticky sidebar in pure CSS
<style>
.wrapper {
display: flex;
justify-content: space-between;
}
.main,
.sidebar {
border: 3px solid black;
padding: 15px;
background-color: #fff;
}
.main {
width: 60%;
height: 150vh;
}
.sidebar {
width: 25%;
height: 25vh;
--offset: 2rem;
flex-grow: 1;
align-self: start;
position: sticky;
position: -webkit-sticky;
top: var(--offset);
}
</style>
<div class="wrapper">
<div class="main">
Main content
</div>
<div class="sidebar">
Sticky sidebar
</div>
</div>
Note the heights of the main and sidebar elements are set using vh
units. 100vh is the height of the current viewport, so setting the height of the main div to 150vh gives it a height that will be 1.5 times that of the screen.