Helping you solve those tough coding problems!

Semi Rant: Absolute Position when it's relative Semi Rant: Absolute Position when it's relative

Published on Mar 21, 2019 by Jamie Munro

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:


<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!

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!

Tags: CSS | Rants | CSS

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP