We have had a few people ask us how we managed to get our sidebar to "stick" as your scroll down the page. So we decided to write a tutorial about it! If you look at one of our longer blog posts you can see that as you scroll down the page the side bar moves with you. We do this to highlight our important information like signing up for our newsletter and providing a quick way for people to get in contact with us should they happen to like out blog.
We have seen tons of implementations of using a plugin to make items sticky throughout the website. However, this is the best way to do it as it is less than 20 lines of CSS, mobile responsive, and you don't need a plugin!
@media only screen and ( min-width: 1405px ) {
.sticky-column {
position: sticky !Important;
position: -webkit-sticky !Important;
top: 150px !Important; /* Change the height from the top here */
}
}
@media only screen and ( min-width: 1100px ) and ( max-width: 1405px) {
.sticky-column {
position: sticky !Important;
position: -webkit-sticky !Important;
top: 150px !Important; /* Change the height from the top here */
}
}
Let's break down this code, shall we?
- We are using CSS media queries to ensure that it is compatible with all different devices.
- If you look at
top: 150px
it is how many pixels that the column is spaced from the top. In our case we are using a fixed header so it looks less than 150px but you will most likely need to adjust it to suit your needs
Then to use it, you simply create a two column layout like you see on this blog posting right in front of you. On the column you want sticky, just add the class .sticky-column
and you are good to go! Another cool feature is you do not need to make a column sticky per se, but you can also make any element sticky as well. Just assign it .sticky-column
and you are good to go. On second thought, if you are going to assign it to elements, change the selector to something more universal to help keep your code organized & clean.