Use CSS to Create a Dynamic Sidebar, with a Fixed Element [Tips & Tricks] | Posted at 11:24 AM
I am working on my new Intrepid Studios website and I came up against a CSS wall. I needed a sidebar that had a "main image" for a design and then list extra images or extra information. However, I wanted it to look cool, so I wanted the image to overlap the header and always appear in the same place.
I needed the design to follow these guidelines:
- The photo must always appear in the same place no matter the height of the header. Sometimes there is no photo.
- Sidebar content must always appear below the header.
- The header has a variable height, so it should push the sidebar content down if it's larger than the photo.
- I want the sidebar content to come after the body content in the HTML, because it's extra information.
Read on fair reader, to see how I solved my problem
The photo above is what it should look like.
And when the header gets bigger:
And finally, when there is no image:
So, how did I accomplish this "magical" feat? It seemed magical and unattainable when I first tackled it, but with help of my awesome manager, mister Zach Johnson, the puzzle was solved.
First, the layout:
<div id="wrapper">
<div id="img">An image</div>
<div id="header"><h1>Header</h1><h2>Sub-title</h2></div>
<div id="content">
<h3>Body Content</h3>
<p>A paragraph</p>
</div>
<div id="sidebar">A paragraph</div>
</div>
Next, the CSS that makes it all happen.
#wrapper {
width: 600px;
}
#img {
float: right;
margin: 10px;
background: white;
width: 180px;
height: 180px;
}
#header {
background: #cdcdcd;
}
#sidebar {
float: left;
width: 180px;
background: #ccc;
margin: 10px;
}
#content {
float: left;
width: 400px;
}
Voila! That's it!
The catch is that your "sidebar" is really two separate entities. One is a container for whatever you need to appear fixed. The other is the flexible part beneath it.
It seems to simple... I can't believe I didn't figure it out. Ah well, I hope this helps some other person out there banging their head against a wall.

Comments
Nice tips & tricks. Thank's
Gunadarma University
Posted by: hanum
On January 13, 2009 8:47 AM
Thanks for programmingtips about Use CSS to Create a Dynamic Sidebar.
Posted by: pdfoxy
On February 21, 2009 10:57 AM
Very helpful and informative tips. CSS has made so many things possible for web designers,and this is certainly one of them!
Posted by: RWH
On September 26, 2009 10:43 PM
Yes, the CSS are really important. This explain is very well. Nice.
Posted by: SEO VCO
On March 13, 2011 2:41 PM
how can you get a background to go with that?
Posted by: tanner
On September 17, 2011 3:59 PM