Floating Sidebar With CSS

Floating sidebars are a great method for keeping menus, share buttons, and other information in front of users as they scroll down the page. There are a number of jQuery plugins that work great for this, but in some cases jQuery might be overkill. For example, if you need to keep informational or help text that is static in front of the user.

A simple way to create a floating sidebar is to use CSS. Take a look at the side bar on the left and scroll down the page this jsfiddle test. Notice, it stays in view the entire time. To achieve this all we have to do is create a div with the following class.

.sideBar
{
position: fixed;
z-index: 1000;
}

The magic is “position: fixed”, it’s what makes the sidebar stay where you want it to. Depending on what else you have on the page, and perhaps if you want it to float outside the container the div is in, I like to use z-index to make sure it overlaps how I want it to.

Now that you have it floating you need to position the div and style it by adding another class like below. In this case the div will float on the left and start below the header of the page.

.sideBar.boxLeft
{
width: 300px;
float:left;
padding: 0px 0px 0px 0px;
left:75px;
background-color:#eee;
top:30%;
}

There you have it, in just a few minutes you have a quick and easy solution for creating a floating sidebar.

Advertisements

About Shawn Sweeney

I'm a father, software developer, and runner. I blog about things related. View all posts by Shawn Sweeney

2 responses to “Floating Sidebar With CSS

  • Ryan

    Position: fixed works, but it resets the margins and fixes the rest of my content. How do I make this rule apply to just the #menu?

    • Shawn Sweeney

      Ryan. If you’re using IE <=6 fixed is not supported. If you're using IE 7 it is supported but you have to make sure your DOCTYPE declaration implements the strict DTD. I have seen some on stackoverflow say loose will work too.

      That aside, it probably has something to do with your overall structure and css. Is the content that you don't want fixed in the same element that has position fixed?

      If you can post an example or a test case on http://jsfiddle.net/ I'd be happy to take a look.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: