Absolute Relative to What?

I ran across a CSS positioning bug today and thought I’d put together this post to explain the most common problem that people I’ve helped come across when trying to position elements absolutely.

When you are positioning an element absolutely, remember that it is absolutely positioned relative to its nearest positioned parent.

So if you have this markup,<div><h1>My Z-Index is bigger than yours</h1></div>And your styles look like this,div {position: relative;background: green;}h1 {position: absolute;top: 30px;left: 30px;}then the h1 would be positioned absolute but within the bounds of the div. So it would show up 30px from the top and 30px from the left of the div not from the top and left of the document.

email_example1

If however, the div wasn’t positioned, then the h1 would appear 30px from the top and left of the document. This can be the cause of hours worth of troubleshooting if you don’t know why your positioned element was displaying the way it was. It can also be really helpful when you want to confine an absolutely positioned element to a particular space. I use it all the time when placing styled quotes around user testimonials. Bam! You just learned something….hopefully this will save you some time and you won’t have to spend hours wondering why your element is misbehaving…which I had to do when I was first learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.