CSS Position Explained
- Static Positioning
- Relative Positioning
- Absolute Positioning
- Fixed Positioning
1. Static Positioning
This is a default position for HTML elements. It is always positioned according to the normal flow of the page. Static positioned elements are not affected by the top, bottom, left, right, and z-index properties.
Example
HTML:
<div class=”parent”>
<div class=”box” id=”one”>One</div>
<div class=”box” id=”two”>Two</div>
<div class=”box” id=”three”>Three</div>
<div class=”box” id=”four”>Four</div>
</div>
CSS:
.parent {
border: 2px black dotted;
display: inline-block;
}
.box {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}
#two {
background: green;
}
2. Relative Positioning
A relative positioned element is positioned relative to its normal position. In the relative positioning scheme, the element's box position is calculated according to the normal flow. Then the box is shifted from this normal position according to the properties — top or bottom and/or left or right.
CSS:
#two {
top: 20px;
left: 20px;
background: green;
position: relative;
}
3. Absolute Positioning
An absolutely positioned element is positioned relative to the first parent element that has a position other than static. If no such element is found, it will be positioned on a page relative to the 'top-left' corner of the browser window. The box's offsets further can be specified using one or more of the properties top, right, bottom, and left.
CSS:
#two {
top: 20px;
left: 20px;
background: green;
position: absolute;
}
4. Fixed Positioning
Fixed positioning is a subcategory of absolute positioning. The only difference is, a fixed positioned element is fixed with respect to the browser's viewport and does not move when scrolled.