Placing elements correctly on web pages is essential for creating a good layout. CSS provides various methods for positioning elements. Below, we'll explain these methods step by step.
An element with static positioning is always placed according to the regular flow of the page. HTML elements have static positioning by default. They aren't influenced by properties like top
, bottom
, left
, right
, and z-index
.
.box {
padding: 20px;
background: #7dc765;
}
An element with relative positioning is placed relative to its original position.
In relative positioning, the element's position is calculated based on the regular flow first. Then, it's shifted from this regular position using properties like top
or bottom
and/or left
or right
.
.box {
position: relative;
left: 100px;
}
Note: A relatively positioned element can be moved and overlap other elements, but it retains the space originally reserved for it in the regular flow.
An element with absolute positioning is placed relative to the first parent element that has a position other than static. If no such element is found, it's positioned on the page relative to the top-left corner of the browser window. You can further specify the box's offsets using properties like top
, right
, bottom
, and left
.
Absolutely positioned elements are completely removed from the regular flow and don't occupy any space among sibling elements. However, they can overlap other elements depending on the z-index
property value. Additionally, an absolutely positioned element can have margins, and these margins don't collapse with any other margins.
.box {
position: absolute;
top: 200px;
left: 100px;
}
Fixed positioning is a subtype of absolute positioning.
The only difference is that a fixed positioned element is fixed relative to the browser's viewport and remains in place when you scroll.
.box {
position: fixed;
top: 200px;
left: 100px;
}
Note: In the case of the print media type, the fixed positioned element is displayed on every page and remains fixed relative to the page box (even in print-preview). IE7 and IE8 only support the fixed value if a <!DOCTYPE>
is specified.