CSS Position
The position property takes an element out of the plain flow of the page. Offset properties such as top and left set the distance from a reference edge.
Shift a heading
The relative value moves the heading from its own place. The top and left offsets set the size of the shift.
.box h2 {
position: relative;
top: 10px;
left: 20px;
}Place a button in a corner
A positioned ancestor is an ancestor element with a position value other than static. The button is placed against the box, its nearest positioned ancestor.
.box {
position: relative;
}
.box button {
position: absolute;
bottom: 8px;
right: 8px;
}Pin the heading
Fixed positioning pins the heading to the viewport, the visible area of the page. Zero top margin removes the default gap above it.
h1 {
position: fixed;
top: 0;
margin-top: 0;
}Example
.box {
position: relative;
}
.box h2 {
position: relative;
top: 10px;
left: 20px;
}
.box button {
position: absolute;
bottom: 8px;
right: 8px;
}
h1 {
position: fixed;
top: 0;
margin-top: 0;
}Key points
- Static: the default position value, where offsets have no effect
- Relative: a position value that shifts an element from its own place
- Absolute: a position value that places an element against its nearest positioned ancestor
- Fixed: a position value that pins an element to the viewport
- An absolute element leaves the flow, and the elements after it close up.
- A relative element keeps its original space in the flow.
In this example, the box becomes a positioned ancestor for its children. The heading inside the box shifts down and right from its own place. The button sits in the bottom right corner of the box. The page heading is fixed at the top of the viewport.
Note
Sticky is a position value that sticks an element in place while the page scrolls.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which position value pins an element to the viewport?