Position
Place elements with static, relative, absolute, fixed, and sticky.
Syntax
position: absolute; top: 0; right: 0;The position property changes how an element is placed:
static— default, normal flow.relative— offset from its normal spot.absolute— positioned relative to the nearest positioned ancestor.fixed— positioned relative to the viewport.sticky— toggles between relative and fixed while scrolling.
Use top, right, bottom, and left to place positioned elements.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer uses position: fixed on a navigation bar so it stays at the top of the viewport as users scroll down the page.
- A designer uses position: absolute inside a position: relative card to place a badge in the card's top-right corner.
- A developer uses position: sticky on a table header row so column labels stay visible as users scroll through a long data table.
More examples
Relative parent and absolute child
Positions a badge absolutely within its card by making the card a relative containing block.
.card {
position: relative;
}
.badge {
position: absolute;
top: 12px;
right: 12px;
background: #c0392b;
color: #fff;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.75rem;
}Fixed navigation bar
Pins the navigation bar to the viewport top with fixed positioning and compensates for it with body padding-top.
.nav {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 60px;
background: #fff;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
z-index: 100;
}
body {
padding-top: 60px; /* prevent content overlap */
}Sticky table header
Makes table header cells sticky so they remain visible below the fixed nav bar while the table body scrolls.
thead th {
position: sticky;
top: 60px; /* offset below the fixed nav */
background: #fff;
z-index: 1;
border-bottom: 2px solid #2965f1;
}
Discussion