Semi Rant: Absolute Position when it’s relative

S

I have long been against absolute position. I always felt it the “lazy” way out. Until recently, I’ve seen the light. Absolute positioning works extremely well inside of a relative position. In fact it works so well, that it reduces my browser testing time because IT IS actually consistent!

Absolute Positioning with CSS

It helps to begin with an example. Please don’t mock me too much as I’m not a designer…

In the above example, there is a black rectangle that has a simple blue background overlapping, but resting outside of the box.

Now, with some basic HTML and CSS watch how simple it is to achieve this with an absolute position element inside of a relative image:

[code]
<div id=”blackbox”>
Content of the black box goes here…
<div class=”bluebar”></div>
</div>
[/code]

Next, some basic CSS is applied to these items:

[code]
#blackbox {
background-color: #000;
color: #FFF;
height: 300px;
width: 300px;
position: relative;
}

.bluebar {
background-color: blue;
height: 200px;
width: 30px;
position: absolute;
right: -15px;
top: 50px;
}
[/code]

The above code will now achieve the exact same effect as in the picture. 15 pixels of the blue bar will be sitting in the black while the other 15 pixels are resting outside of it.

This same effect could be achieved without the absolute positioning; however, it would require using floating elements, some margin or padding to get the exact positioning. And if you have done a lot of web development, it does not always achieve the same look in the various browsers!

After fighting it for years, I’m officially a fan of absolute positioning elements with CSS – as long as it is relative to another element!

Other useful articles

About the author

By Jamie

My Books