Relative Positioning
Last updated
Last updated
If we want to precisely position an element, floats or inline-block elements won’t do the trick.
Floats, which remove an element from the flow of a page, often produce unwanted results as surrounding elements flow around the floated element. Inline-block elements, unless we’re creating columns, can be fairly awkward to get into the proper position. For these situations we can use the position
property in connection with box offset properties.
The position
property identifies how an element is positioned on a page and whether or not it will appear within the normal flow of a document. This is used in conjunction with the box offset properties—top
, right
, bottom
, and left
—which identify exactly where an element will be positioned by moving elements in a number of different directions.
By default every element has a position
value of static
, which means that it exists in the normal flow of a document and it doesn’t accept any box offset properties. The static
value is most commonly overwritten with a relative
or absolute
value, which we’ll examine next.
The relative
value for the position
property allows elements to appear within the normal flow a page, leaving space for an element as intended while not allowing other elements to flow around it; however, it also allows an element’s display position to be modified with the box offset properties. For example, consider the following HTML and CSS:
Here the second <div>
element, the element with the class of offset
, has a position
value of relative
and two box offset properties, left
and top
. This preserves the original position of the element, and other elements are not allowed to move into this space. Additionally, the box offset properties reposition the element, pushing it 20
pixels from the left
and 20
pixels from the top
of its original location.
With relatively positioned elements, it’s important to know that the box offset properties identify where an element will be moved from given its original position. Thus, the left
property with a value of 20
pixels will actually push the element towards the right, from the left, 20
pixels. The top
property with a value of 20
pixels, then, will push an element towards the bottom, from the top, 20
pixels.
When we position the element using the box offset properties, the element overlaps the element below it rather than moving that element down as the margin
or padding
properties would.