This post will take 2 minutes to read.
There are four potential values for the
position property (ignoring
inherit) which are
fixed. Now, while this article will be focusing on the
relative value, it is important to understand some key bits of information about the other values:
- Static positioning (the default value) is actually a lack of positioning.
- Absolute or fixed positioning removes the element from the flow of the document.
- Absolutely positioned elements are positioned relative to nearest positioned ancestor element.
Right, now that you have wrapped your head around that, let’s talk about the uses for relative positioning. There are three main instances where it comes in handy:
- When you want to move an element (while keeping it in the flow of the document, but without disturbing any other elements).
- When you want to define a containing box for absolutely positioned descendant elements.
- When you need an element to have positioning so that you can use
Moving an element
Elements are naturally rendered in the flow of the document, and as such, they interact (i.e. they affect the position of each other). This is generally a good thing, as most of the elements on your page have a relationship with the elements around them. For instance, a footer being pushed down by your main content.
Sometimes though, you want to move an element without it affecting any of the elements around it. This is where
position: relative; comes in handy. When using relative positioning with the
left properties, it is only the generated box that is actually shifted; the element still remains where it was in the flow of the document. Keep in mind that this can often result in overlapping elements.
Also, it is important to remember that the
left properties can’t change the size of a relatively positioned element (they can if the element is absolutely positioned).
Containing absolute descendants
When positioning an element absolutely—as it is removed from the flow of the document—the
left properties don’t act as they would on a relatively positioned element. These properties are now based on the nearest positioned ancestor (or the root element, if there are none). This means that if you are giving an element a position of absolute and you want to confine it to a certain ancestor, setting
position: relative; on that ancestor will do the trick without affecting the flow of that element.
The terminology is a little tricky here as an element with
position: static; appears as though it has a position set, but as static positioning is in fact no positioning at all, static elements can’t be containing boxes for absolute elements.
z-index is only respected on elements that have a position set. So if you don’t want to remove an element from the flow of the document, but want to use
z-index, relative positioning is your friend.