You learn something new everyday! Part 2

So this morning, I headed over to Lynda.com for some refresher training on CSS. There were a couple things I could figure out. I'm still working through those issues, but learned something really cool, and something really useful to know...

A better way to position columns

I had been positioning columns in my various web designs using float positioning. I'd float one column left, and the other right. A third column could even find it's way between the floating columns.

While this works fine, it was challenging sometimes. Using absolute positioning is MUCH better!

The key to absolute positioning, is to include a containing block using relative positioning. The terms are totally confusing, but absolutely positioned elements are positioned relative to their containing block. If you don't use a containing block, the default is the browser window itself. This will not give you the look you're going for.

Here's an example:

This is the first column. It has a red background, white text, and 10px of padding on each side.
This is the second column. It has a white background, black text, and 5 px of padding.
This is the third column. It has a blue background, white text, and no padding.

And here's the code:


<style>
#bodyContainer {
position:relative;
width:600px;
}
#leftColumn {
position:absolute;
top:0;
left:0;
width:180px;
padding:10px;
background-color:red;
color:#fff;
}
#middleColumn {
position:absolute;
top:0;
left:200px;
width:190px;
padding:5px;
}
#rightColumn {
position:absolute;
top:0;
left:400px;
width:200px;
background-color:blue;
color:#fff;
}
</style>

<div id="bodyContainer">
<div id="leftColumn">This is the first column.  It has a red background, white text, and 10px of padding on each side.</div>
<div id="middleColumn">This is the second column.  It has a white background, black text, and 5 px of padding.</div>
<div id="rightColumn">This is the third column.  It has a blue background, white text, and no padding.</div>
</div>

Padding ADDS to an element's width

I thought I had a pretty good handle on the box model. I knew margin was applied outside the box, and padding was inside the box. I thought the box was defined by it's height and width attributes.

I was wrong.

Padding actually adds to the height and width. So if you have a div set to width:250px, and give it 10px padding on all sides, it's overall width becomes 270px. 10+250+10=270

I wasn't sure what was giving me fits lining up some of my divs. Now I know!