What are the differences between relative, absolute, and fixed positioning?
Anahera
13 June, 2024
Positioning allows you to control the layout and placement of elements on a page.
Relative
Moves an element relative to its original position and keeps it in the page flow.
To put it simply, adding a position of relative will keep the element in the same position and will move around based on this starting point. When you add properties like top or bottom, you will move the element from it's original position.
- div.relative {
- position: relative;
- top: 0;
- left: 0;
- }
Absolute
Positions an element relative to its nearest positioned ancestor and removes it from the document flow.
This property first removes the element from it's orginal spot on the page, and will be moved based on an ancestor element that has a position value other than static.
The below example shows how the Absolute box is positioned in realtion to the ancestor, the Absolute box.
Another example is the closed quotation mark in the footer. It's nearest ancestor with a position property is the footer container, so it has been moved around in relation to the footer container.
- div.absolute {
- position: absolute;
- top: 0;
- right: 0;
- }
Fixed
Positions an element relative to the viewport, keeping it in place during scrolling, and removes it from the document flow.
Again, this position removes the element from it's original spot on the page, and any movement will be in relation to the viewport/screen. So "top: 10px" would move the element 10px down from the top of your screen.
Use cases for position: fixed culd be keeping your navigation bar at the top of the page.
- div.fixed {
- position: fixed;
- bottom: 0;
- right: 0;
- }
Some kinda call to action copy goes here.