CSS Positioning
Overview
CSS positioning controls how elements appear on a webpage. There are four types:
- Static
- Relative
- Absolute
- Fixed
The following sample files will be used for the examples:
Static Positioning
This is the default positioning of HTML elements.
- Elements appear in normal document flow
- No special position applied
- Left, top, right, bottom properties have no effect
Static positioning means elements appear in the order they are written in HTML.
In the example below, a box is defined. No special keywords is used and iit will be displayed as is.
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
}
Relative Positioning
Moves an element relative to its original position.
- Uses
top
,left
,right
,bottom
- Shifts from default placement
- Other elements remain unchanged
Example:
.relative {
position: relative;
top: 10px;
left: 20px;
}
The element moves 10px down and 20px to the right from its original spot.
Absolute Positioning
Positions an element relative to the nearest positioned ancestor.
- If there's no positioned ancestor, defaults to page
- Removed from normal document flow
- Uses
top
,left
,right
,bottom
Example:
.absolute-container {
position: relative;
width: 300px;
height: 200px;
border: 1px solid #000;
}
.absolute {
position: absolute;
top: 50px;
left: 50px;
}
In this example, the box with the class .absolute
is positioned 50px from the top and 50px from the left of its closest positioned ancestor, which is the .absolute-container
.
Z-Index
Another aspect of the absolute positioning is the z-index
, which controls the stacking order of elements.
- Determines which element goes on top of which
- Higher values appear above lower values
- Works with
relative
,absolute
,fixed
Every element has a default z-index
of 0
. If you want to put element A behind element B, you need to set the z-index
of element A to -1
. To put it in front, set the z-index
to a number higher than 0
.
Example:
.box {
position: absolute;
z-index: 10;
}
A higher z-index
makes an element appear on top of others.
Fixed Positioning
Keeps an element fixed relative to the browser window.
- Stays in place even when scrolling
- Uses
top
,left
,right
,bottom
- Removed from normal document flow
Example:
.fixed {
position: fixed;
bottom: 10px;
left: 10px;
}
The element remains at the bottom-left corner of the browser, even when scrolling.
Sticky Positioning
Sticky positioning makes an element stick to a specific position as you scroll, but only within its parent container. Once you scroll past it, it moves with the page content again.
.sticky {
position: sticky;
top: 0;
background-color: yellow;
padding: 10px;
}
In this example, the .sticky element will stay at the top of the viewport as you scroll, until the parent container's boundary is reached.