Relative Positioning

An element whose position property has the value relative is first laid out just like a static element. The rendered box is then shifted vertically (according to the top or bottom property) and/or horizontally (according to the left or right property).

The properties top, right, bottom, and left can be used to specify by how much the rendered box will be shifted. A positive value means the box will be shifted away from that position, towards the opposite side. For instance, a left value of 20px shifts the box 20 pixels to the right of its original position. Applying a negative value to the opposite side will achieve the same effect: a right value of -20px will accomplish the same result as a left value of 20px. The initial value for these properties is auto, which makes the computed value 0 (zero)—that is, no shift occurs.

Evidently, it’s pointless to specify both left and right for the same element, because the position will be over-constrained. If the content direction is left to right, the left value is used, and right will be ignored. In a right-to-left direction, the right value “wins.” If both top and bottom are specified, top will be used and bottom will be ignored.

Since it’s only the rendered box that moves when we relatively position an element, this positioning scheme isn’t useful for laying out columns of content. Relative positioning is commonly used when we need to shift a box a few pixels or so, although it can also be useful, in combination with negative margins on floated elements, for some more complex designs.

Control Your Containing Blocks
One side effect of relative positioning is quite handy: a relatively positioned element is “positioned,” which means it becomes the containing block for any absolutely positioned descendants. This gives us an easy-to-use tool for controlling the position of our containing blocks: just set position to relative without moving the box at all.

Learn HTML5 Online

Get all SitePoint books and courses with a Learnable membership. Start building future-proof websites that are faster, more powerful, and easier to maintain.

No Reader comments

Comments on this post are closed.