Webistrate - Draw Your Own Conclusions

HTML: Absolute Position…when it’s relative

Posted by Jamie Munro | December 26, 2011 | Tags: ,

Share

I have long been against absolute position.  I always felt it the “lazy” way out.  Until recently!  I’ve finally 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!

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:

<div id="blackbox">
Content of the black box goes here…
<div class="bluebar"></div>
</div>

Next, some basic CSS is applied to these items:

#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;
}

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!

Summary

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!

Share


Random Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books