Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a fixed / sticky sidebar in CSS / JS?

I'm trying to create a website with main content area and a sidebar, something like here on Stack Overflow. The goal is that when you scroll down, the sidebar stays visible.

I have seen two approaches to this:

  1. position:fixed;
  2. JavaScript manipulation with the DOM

Approach no. 1, as far as I know, will have a problem when the viewport is smaller than the sidebar contents so I guess that can't be used reliably and JavaScript scripts that I have seen are usually animated or generally "slow" (you can see that there is redrawing going on after each scroll).

Can someone point out a JavScript library / CSS approach that would not suffer from the aforementioned issues?

Edit: an example would be this page but with the sidebar sticking to the top without an animation and correctly handling the situation when the sidebar is higher than content / viewport.

like image 424
Borek Bernard Avatar asked Mar 11 '12 19:03

Borek Bernard


People also ask

How do you make a sticky sidebar in CSS?

You can either make a custom stylesheet specifying the sidebar style or you can add an inline CSS code "position: sticky" to your sidebar element/container.

How do I keep my sidebar fixed?

The easiest way to handle this is just to use CSS fixed positioning. Our sidebar is within a #page-wrap div with relative positioning, so the sidebar will set inside there, then we just push it over into place with margin. With this technique, the sidebar stays solidly in place as you scroll down the page.

How do you use a sticky sidebar?

Add the widget you wish to make sticky to the sidebar area. Then, click on that widget, check the Fixed Widget box, and save changes. And it's as simple as that. Any widget you mark as “fixed” will now follow the user in a sticky sidebar as they scroll through your content.

What is a sticky sidebar?

A sticky sidebar is a web design technique to keep the sidebar on the screen even if the user has scrolled past the position where it initially displayed.


1 Answers

I don't like heavy JS solutions, so important thing to ask is - preferred compatibility. In IE8+ it is possible instead of

var $window = $(window),
    $sidebar = $(sidebar);

$window.on('resize', function(){
    $sidebar.height($window.innerHeight());
});

$window.resize();

do something like this (pure CSS solution):

#sidebar {
    position: fixed;
    left: 0; /* or right */
    top: 0;
    bottom: 0;
    overflow: auto;
}

When you have top&bottom / left&right value at the same time, box will be stretched. (JSFiddle demo)

like image 82
Zdenek Kostal Avatar answered Oct 08 '22 06:10

Zdenek Kostal