Position: relative; and Floats
Last week I came across a problem where I needed to float a container, but I also needed to position something absolutely inside that container. Now I suppose I could’ve done something like this:
<div id="outside_wrapper">
<div id="inside_wrapper">
<p id="float">Some floated content</p>
<p id="absolute">Some absolutely
positioned content</p>
</div>
</div>
Then in my CSS I could do something like this:
div#outside_wrapper {
width: 700px;
float: left;
}
div#inside_wrapper {
width: 700px;
position: relative;
}
p#float {
float: left;
}
p#absolute {
position: absolute;
right: 0;
bottom: 0;
}
But why? Because as it turns out, this works just as well:
<div id="outside_wrapper">
<p id="float">Some floated content</p>
<p id="absolute">Some absolutely
positioned content</p>
</div>
div#outside_wrapper {
width: 700px;
float: left;
position: relative;
}
p#float {
float: left;
}
p#absolute {
position: absolute;
right: 0;
bottom: 0;
}
Maybe you already knew this and I’ve just been in the dark, but I was fairly excited about this. It is entirely possible to relatively position an element at the same time you are floating it. Not only will this allow you to absolutely position elements inside floated wrappers, but you can also float an element then position it relative to where it would normally float and even apply a z-index to the element. 












Yeah I didn’t actually learn it, I stumbled across it when looking into UL’s and LI’s. Where you don’t need to include them in a div, just ID them and assign them the same attributes you would as if they were a div. Quite helpful. Thanks for sharing it to the masses.
Well yeah, I knew that. But the fact that you can position an element relatively at the same time you’re floating it was a new discovery. I assumed that you can only be using one type of positioning per element at a time (float, relative, or absolute), but it appears that floats and relative positioning can both be applied to the same element.
That should be an error in the CSS… Technically the second position delcaration should over-ride the first… shouldn’t it?
@Luke: If they were both actual position properties, then it should cause an error. But using floats with position is fine. I actually asked Nathan about it today as I wasn’t completely sure if you were supposed to do that, and as he told me, floats control what happens around the element, and position controls what happens to the element.
Ahh… very good to know!