CSS – Sticky Sidebar
Sometimes when building a site that has filters or relies heavily on sidebar navigation you might want to have the sidebar content follow you down the page as you scroll. This is a simple way to implement within your html using just modern CSS and no Javascript. A special thanks to Claire who put together this awesome code example:
Codepen Example
Step 1: Create your HTML
To start create a page with the folowing HTML.
<div class="wrapper">
<div class="main">
<h2>Main content</h2>
<p>Scroll down the page!</p>
<h3>How to recreate this</h3>
<p>
Position the columns with flex. Then apply two lines of CSS to the sidebar to make it sticky:
<pre>
.sidebar {
position: sticky;
top: 0;
}
</pre>
Include <code>position: -webkit-sticky;</code> for Safari.
</p>
</div>
<div class="sidebar">
<h3>Sticky sidebar</h3>
<p>I will follow you!</p>
<p><a href="https://caniuse.com/#search=sticky">caniuse stats</a>
</div>
</div>
Step 2: Add the Styles
Next to unlock the magic add your CSS:
.sidebar {
width: 25%;
height: 25vh;
min-height: 200px;
overflow: auto;
position: sticky;
top: 5%;
}
.main {
width: 60%;
height: 200vh;
min-height: 1000px;
display: flex;
flex-direction: column;
}
.main,
.sidebar {
border: 5px solid #222;
background-color: white;
border-radius: 10px;
color: #222;
padding: 15px;
}
.wrapper {
display: flex;
justify-content: space-between;
}
body {
padding: 3%;
background-color: #ccc;
font-size: 20px;
box-sizing: border-box;
font-family: Lato, sans-serif;
}
code, pre {
background-color: #ccc;
padding: 0 3px;
border-radius: 5px;
}
.bottom {
justify-self: bottom;
}
Or if you are feeling sassy here is the SCSS version:
$color-dark: #222;
$color-body: #ccc;
$color-background: white;
.sidebar {
width: 25%;
height: 25vh; // experiment with this value, try changing to 110vh
min-height: 200px;
overflow: auto;
position: -webkit-sticky;
position: sticky;
top: 5%;
}
.main {
width: 60%;
height: 200vh;
min-height: 1000px;
display: flex;
flex-direction: column;
}
.main,
.sidebar {
border: 5px solid $color-dark;
background-color: $color-background;
border-radius: 10px;
color: $color-dark;
padding: 15px;
}
.wrapper {
display: flex;
justify-content: space-between;
}
// Decoration for demo
body {
padding: 3%;
background-color: $color-body;
font-size: 20px;
box-sizing: border-box;
font-family: Lato, sans-serif;
}
code, pre {
background-color: #ccc;
padding: 0 3px;
border-radius: 5px;
}
.bottom {
justify-self: bottom;
}

Leave a Reply
Want to join the discussion?Feel free to contribute!