CSS Web Design Tip: Absolute In Relative

CSS TipCSS does some things that I just don’t quite understand. One thing it does that ticks me off is how absolute positioning works. When positioning elements inside, say a header, you will generally use absolute positioning. However, that alone will not get the results you were expecting, but luckily there is one neat little trick to fix that.

When most people make a CSS header it will may look a bit like this:

.header {
width: 100%;
height: 130px;
margin: 0;
padding: 0;
background-color: #81a0d2;
}

.header h1 {
padding: 0;
margin: 0;
font: normal 1.2em/1.2em Verdana;
color: #1c55b0;
position: absolute;
right: 55px;
top: 25px;
}…etc

However, all it takes is a simple page load to realize your layout isn’t working right. When it first loads it may look alright but if you stretch your browser window it will eventually look like this:

CSS Absolute In Relative

Yeah, YUCK!

Luckily the fix is incredibly easy. Simply insert “position: relative” into the section for your header:

.header {
width: 100%;
height: 130px;
margin: 0;
padding: 0;
background-color: #81a0d2;
position: relative;
}

And now it should work exactly as expected:

CSS Absolute In Relative 2

Why does it work? I haven’t a clue, it just does.

Please subscribe, or else I will cry. Do you really want to make a programmer cry?

Leave a Reply

Note: By submitting your comment you agree to this blog's comment policy.

If you want a little icon next to your name - sign up for one at Gravatar.