If you often surf the Internet, you may find a lot of pages with a fixed element, or a fixed sidebar. That means, the element (for example shopping cart, Buy button, or the email subscription fields) follows when you scroll up or down, which catches your attention easily. This article will show you how to do it with only several lines of CSS.
Although somebody may say it is one of the web tricks to increase customer engagement, I still think fixed sidebar is a useful feature for us as a user of the site.
Let’s think about Excel or Google Spreadsheet, the feature to freeze columns and rows brings about a lot of help in understanding the document, mostly statistics records. Since the top row stays on top all the time, we don’t need to scroll up to see what the content is about.
1. The fixed sidebar
Recently I made changes to a blog template.
Normally, there were two columns in the template: one displays the main entry content and the other is a sidebar of about 1/3 of the page.
Originally, the sidebar is static and it would not make any move when visitors scroll to the end of the page. This makes the sidebar look empty if the blog content is really really long.
So, I would like to make it float, so that the sidebar could increase web engagement and to make the blog post looks balanced even though the readers will scroll down a lot.
The plan for a floating sidebar is:
- The sidebar content does not follow yet when people visit the site.
- When people scroll down to a section (maybe the starting point of the blog entry content), sidebar becomes fixed.
- After people pass the content blog and come to other section, for example the footer, sidebar stops following and stay within the blog entry section.
Sounds good? Let’s continue
2. Make sidebar fixed with position: sticky
Earlier, I thought that we can make a sidebar fixed with position: fixed.
But it would be complicated in this situation. Not like a Shopping cart or Buy button, a sidebar is quite a relative element of a website. It would be weird if the sidebar with social channels icons or advertising stays fixed all the time. So it is better to make it fixed only within a section.
But for position: sticky, things are much more easier. The difference between fixed and sticky is that the sticky only fixed within an element in which it is related to.
So the important things are:
- Set a top and bottom
- Cross-browser safety with position: sticky.
For simple live demo and modification, please visit here: See floating sidebar live demo from JSFiddle.
In the Fiddle, I use Bootstrap. So, the CSS of Bootstrap already included. Link to Bootstrap CSS CDN.
Result (I also change something else, so you will see the sidebar content also changes compared to the early image):
I hope this post help. Any questions or improvement recommendations please leave in the comment section. Thank you for reading!