CSS offset properties and static position

DrStrangeLove picture DrStrangeLove · Apr 9, 2011 · Viewed 25.2k times · Source

Are offset properties (left, top, bottom, right) only for non-static positions?

Can they be applied to a statically positioned element? If so, what are the differences from applying them to non-statically positioned elements?

Answer

clairesuzy picture clairesuzy · Apr 9, 2011

to offset an element it's position has to be position:relative

the co-ordinates, top, right, bottom and left serve different purposes depending on if the element is relatively or absolutely positioned.

When is an element offset as opposed to moved?

when you actually offset using position: relative; the element is not removed from the flow, and indeed the space that the element would have taken up if it had remained static (the default) is still reserved for it, therefore you have just offset it from it's original position. Any element following it will appear where it would have done even if you hadn't offset it's predecessor - like this example

Moving, not offsetting

If however you actually want to move an element, then it needs to be removed from the flow, so there is no space reserved for it, and then that's when you use position:absolute; or fixed.. that is the difference

Summary

  • static is the default, and you just use margins to move it around, it will ignore co-ordinates and z-index

  • relative is reserved space, co-ordinates will offset it from it's original space

  • absolute will remove the element from the flow and the co-ordinates will be calculated according to it's containing block, which is the nearest relatively positioned ancestor (or the body element if no relatively positioned ancestors exist)

  • fixed does not have a containing block, i.e. you can't specify which element it should be positioned in relation to, it will just fix itself in relation to the viewport

and finally an element will not accept a z-index if it's position is the default of static, so position: relative; without any co-ordinates applied is similar to static, but it is useful for z-indexing and being a containing block for absolutely positioned elements