Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement fixed sidebar correctly?

Tags:

css

sidebar

I'm trying to accomplish this design: example design Where the sidebar will be fixed, but the right side (the main content) will scroll vertically (and potentially horizontally if the user's browser window is smaller). What is the best way to achieve this?

I tried making the sidebar be "fixed" with a fixed width of 200px, and then the main content just has a margin-left of 200px. However, if the user's browser is then smaller than the main content, the sidebar overlaps all the content as the user tries to scroll horizontally.

Is there a smarter way to achieve this? Thanks!

like image 306
Jakemmarsh Avatar asked Mar 23 '13 18:03

Jakemmarsh


People also ask

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 I make my sidebar sticky?

Just call new StickySidebar('ELEMENT') on the element that you want it to be sticky when scrolling up/down inside their parent. var sidebar = new StickySidebar('#sidebar', {topSpacing: 20}); Scroll It!


1 Answers

Use the content div as your container for the page.

 .sidebar {      position: fixed;      width: 200px;      height: 400px;      background: #000;  }  .content {      margin-left: 200px;      height: 500px;      width: auto;      position: relative;      background: #f00;      overflow: auto;      z-index: 1;  }  .info {      width: 1440px;      height: 300px;      position: relative;      background: #f55;  }  <div class="sidebar"></div> <div class="content">     <div class="info"></div> </div> 

Your content will need to be the container to put the page in. The values here are my test to see if I am correct in this. If your width and height exceeds the values you set for content, the scroll bars will appear.

Have a fiddle: http://jsfiddle.net/djwave28/JZ52u/


edit: responsive sidebar

To have a responsive fixed sidebar, simply add a media-query.

Example:

@media (min-width:600px) {    .sidebar {      width: 250px;    }    .content {      margin-left: 250px;    }  } 

Here's another fiddle: http://jsfiddle.net/djwave28/JZ52u/363/

like image 79
Daniel Avatar answered Sep 22 '22 17:09

Daniel