Float and position: relative

Hello,

I’ve noticed that float and position: relative are often associated. As in:


element {
position:relative;
float: left;
}

What is position:relative used for? Is it to trigger some hasLayout thingy?

:slight_smile:

position relative is used when you want to position another element absolutely inside that element.

Example: if you just position:absolute; an element with top:5px; it will appear 5px from the top of the page.
If you have an element lower down for example your footer you use position:relative; on the footer then position:absolute; on an element inside it with top:5px; and it will appear 5px from the top of the footer.

As well as already mentioned above it is also used so that you can apply z-index as only positioned elements can have z-index applied. Just adding position:relative is often enough to make the element appear on top of static elements anyway and indeed if you are using negative margins in IE the chances are that your float will need position:relative or the negative portion goes missing.

The float could also itself be relatively positioned in that you could float something right and then offset it with relative positioning using co-ordinates and not affect the flow of the page from the original position. Relative positioning moves an element visually and not physically so you can think of it as the element is always where it was but it looks as though it is somewhere else. offsetting with relative positioning is used for subtle effects most of the time and not for structural layout.

If you don’t have any of the above criteria then there is no need to add position:relative at all. There should always be a reason why you have added it.:slight_smile:

A floated element that is not relatively positioned isn’t absolutely positioned; is it ?

What would be the difference between


element
 {
position:relative;
float: left;
}

and


element
 {
float: left;
}

No not unless you have added position:absolute to it and then the float is redundant because absolute positioning wins out.

What would be the difference between


element
 {
position:relative;
float: left;
}

and


element
 {
float: left;
}

The differences would only be evident on the criteria that we have already mentioned above.

If the element has no absolute children or doesn’t overlap any other elements then there will be no visual difference. It’s only when you want to create a stacking context for absolutely placed children, or if you want to dictate the stacking order, or if you are going to move it with co-ordinates

No. The default is position:static