CSS positioning trick

Trick is perhaps a strong word for it, but I picked up on a nice technique recently that has helped a great deal in the positioning of certain elements. I can’t remember exactly where I read it, it may have been A List Apart, but if anyone can remind me, I’ll happily update this post :)

Now, the technique, basically it involved using position:absolute, but being able to have a bit more control of it inside a page.

If you’ve tried using position:absolute, you may have noticed it have some problems, especially when you can’t be sure where and element is going to end up.
It can work ok if you have a left aligned site and fixed width/height elements, but introduce any level of flexibility, and it starts being less useful.

That is, unless we introduce a new point of reference for it.
Usually, position:absolute uses the top left corner of the screen as it’s start point, but, we can use some other CSS to change this.

Lets say you want to align something in the bottom right of a particular div. We can’t usually use something like
position:absolute;
right:0;
bottom:0;

because that will end up at the bottom right of the whole screen.

But, if we apply position:relative to the div, we then reset how position:absolute works.

The box that position:absolute is now applied to, is the div, not the entire screen.
So a quick example of how I’ve used it recently.

I need to position an image in the bottom right of a div. I already had a background image applied, and it needed to be linked anyway, easier to have an wrapped in an .

So I had something like

Here’s some text, blah blah blah

with CSS like

div.box{
position:relative;
padding-bottom:15px;
}

div.box img{
position:absolute;
right:0;
bottom:0;
}

Now the img will be positioned in the bottom right of the div, not the bottom right of the page.
When using position:absolute, it either uses a container box with position:relative applied as it’s frame, or the entire page, if there is no container box with position:relative.

It can make position:absolute a lot more useful and flexible in more types of design and is a command I no longer try and avoid so much.

Leave a Reply