CSS3 Layout: Positioning
The position
property in CSS is a fundamental tool for controlling the placement of elements on a web page. It works in conjunction with other properties like top
, right
, bottom
, left
, and z-index
to achieve precise layouts.
Understanding the `position` Property Values
The position
property can take several values, each affecting how an element is rendered and positioned:
1. static
(Default)
Elements with position: static;
are positioned according to the normal flow of the document. They are not affected by the top
, right
, bottom
, or left
properties.
.element {
position: static; /* This is the default value */
}
2. relative
Elements with position: relative;
are positioned according to the normal flow of the document. However, they can then be offset from that position using the top
, right
, bottom
, and left
properties. The original space occupied by the element in the normal flow is preserved.
The offset is relative to the element's normal position.
Parent container (relative)
Original space remains.
.element {
position: relative;
top: 20px;
left: 30px;
}
3. absolute
An element with position: absolute;
is removed from the normal flow of the document. Its position is determined by the nearest positioned ancestor (an ancestor whose position
property is anything other than static
). If no positioned ancestor exists, it is positioned relative to the initial containing block (usually the <html>
element).
The top
, right
, bottom
, and left
properties define the offset from its containing block.
Parent container (relative)
Removed from normal flow.
.parent-container {
position: relative; /* Important for absolute positioning */
}
.element {
position: absolute;
top: 30px;
right: 30px;
}
4. fixed
An element with position: fixed;
is also removed from the normal flow of the document. However, unlike absolute
positioning, it is positioned relative to the viewport (the browser window). This means it will stay in the same place even when the page is scrolled.
The top
, right
, bottom
, and left
properties define the offset from the viewport.
Scroll down to see the fixed element stay in place.