Archive for the ‘Back to Basics’ Category

CSS Positioning Techniques for Nested DIVs

Tuesday, March 17th, 2009

Positioning elements with CSS can be quite tricky to the untrained user. To be honest, a lot of CSS ends up being trial and error simply because what works in one browser, probably looks different in another (thank you IE!). Setting up page layouts with nested DIVs can be easy, but you need to make sure you specify the right attributes at the right time to get the desired results. In the quick “Back to Basics” tutorial below, I will describe how CSS is rendered using the “position” attribute, and the pitfalls of forgetting to use it.

HTML Setup

The HTML code has been setup as simply as possible. A “container” DIV which holds within it another DIV called “rectangle”.

<div id=”container”>

<div id=”rectangle”></div>

</div>

Nested DIVs – No Positioning

step-1

As you can see, the “rectangle” DIV is positioned relative to its container DIV. If you added a margin around the “container” DIV for example, the “rectangle” DIV would reposition itself as well – in the same spot as it is currently in.

#container
{
border: 3px solid #000000;
width: 430px;
height: 200px;
margin: 50px;
}

#rectangle
{
background-color: #000000;
width: 300px;
height: 150px;
}

Adding Positioning

In the previous section of code, the “rectangle” DIV was positioned relative to its container DIV. We didn’t specify any “position” attribute in the CSS, it is assumed that it should render inline. Now we’re going to add a position:absolute; attribute to the “rectangle” DIV and tell it to position a little more specifically at left: 10px;

step-2

What happens now is the “rectangle” DIV no longer sees that its container is valid. It actually positions itself left:10px from the page, not the DIV it sits in. There is one last step we need to take:

#container
{
border: 3px solid #000000;
width: 430px;
height: 200px;
margin: 50px;
position: relative;
}

#rectangle
{
background-color: #000000;
width: 300px;
height: 150px;
position: absolute;
left: 10px;
}

step-3

Now we’ve added a position:relative attribute to the “container” DIV, and hey presto! the “rectangle” now realises it should adhere to the rules and limits of its container (as best it can)… You can also use position:relative within the “rectangle” DIV if you so wished, you’d get the same result – however it all depends on what you want to achieve…

Round Up

This issue flummoxed me for hours when I began developing with Nested DIV layouts, yet it was so simple to fix. Always remember to set the parent DIV position to relative if you want to position DIVs inside is absolutely, otherwise, it’s head against wall time :)

Tools to help you learn…

Learning jQuery 1.3

Learning jQuery 1.3

CSS - The Missing Manual

CSS - The Missing Manual

jQuery UI 1.6

jQuery UI 1.6