HTML & CSSMedium
Position types?
CSS has five position types: static, relative, absolute, fixed and sticky. They differ in whether the element stays in the normal flow and what it is positioned relative to: its normal spot, the nearest positioned ancestor, the viewport, or a scroll container.
Detailed comparison
| Value | In flow? | Positioned relative to | Typical use |
|---|---|---|---|
static | Yes | n/a (offsets ignored) | Default |
relative | Yes (space kept) | Its own normal position | Small nudges; anchor for absolute children |
absolute | No | Nearest non-static ancestor (else the initial containing block) | Badges, tooltips, dropdowns, overlays |
fixed | No | The viewport* | Sticky headers, floating buttons, toasts |
sticky | Yes | Its scroll container, within the parent's bounds | Table headers, section titles, sidebars |
*Unless an ancestor has transform, filter, perspective, contain or will-change: transform; then fixed behaves like absolute relative to that ancestor. This is a common bug in modals inside animated containers.
Sticky gotchas
- It needs an offset (
top: 0), otherwise it never sticks. - It only sticks within its parent's box; a short parent means a short sticky range.
- An ancestor with
overflow: hidden,autoorscrollbecomes the scroll container and can stop it from sticking to the page.
Modern additions
- Anchor positioning (
anchor-name,position-anchor,position-area) positions tooltips relative to another element without JavaScript, in supporting browsers. - The Popover API and
<dialog>render in the top layer, avoidingz-indexandoverflowclipping issues entirely.
Code example
html
1<style>2 body { font-family: system-ui; }3 .scroller { height: 180px; overflow: auto; border: 2px solid #0b1020; }4 .scroller h3 { position: sticky; top: 0; margin: 0; background: #ffd84d; padding: 6px; }5 .scroller p { margin: 6px; }6 .wrap { position: relative; height: 80px; border: 2px dashed #2b4bff; margin-top: 12px; }7 .abs { position: absolute; bottom: 8px; right: 8px; background: #2b4bff; color: white; padding: 4px 8px; }8 .transformed { transform: translateZ(0); position: relative; height: 80px; border: 2px dashed #e11d48; margin-top: 12px; }9 .fixed { position: fixed; top: 4px; left: 4px; background: #e11d48; color: white; padding: 4px 8px; }10</style>11<div class="scroller">12 <h3>Section A (sticky)</h3><p>One</p><p>Two</p><p>Three</p><p>Four</p>13 <h3>Section B (sticky)</h3><p>Five</p><p>Six</p><p>Seven</p><p>Eight</p>14</div>15<div class="wrap">relative parent<span class="abs">absolute child</span></div>16<div class="transformed">17 transformed parent18 <span class="fixed">fixed, but trapped by the transform</span>19</div>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.