Absolute positioning and containing blocks
Definition and purpose
Absolute positioning removes a box from normal flow and locates it using a containing block. A positioned ancestor commonly establishes this reference.
Card badge
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a { position: relative; width: 200px; height: 80px; } #child { position: absolute; top: 10px; right: 10px; width: 50px; } </style> </head> <body> <div id="a"> <span id="child">Badge</span> </div> <div id="b">After</div> </body></html>The badge aligns inside the card; B follows the card.
Syntax and mental model
Use position: relative on a card and position: absolute; top: 8px; right: 8px on its badge. For a typical positioned block ancestor, its padding edge defines the containing block. Opposing insets with auto width can stretch a non-replaced box.
Stretch with insets
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a { position: relative; width: 200px; height: 60px; } #child { position: absolute; left: 20px; right: 30px; } </style> </head> <body> <div id="a"> <span id="child">Badge</span> </div> <div id="b">After</div> </body></html>Auto width fills the remaining 150px.
Common mistakes
The immediate DOM parent need not be the containing block. Reserve room for overlays so they do not obscure reading content.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Static and relative positioning. Next lesson: Fixed and sticky positioning.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Absolute positioning and containing blocks — knowledge check
Five questions on absolute positioning and containing blocks.
Does an absolute box reserve normal-flow space?
What commonly establishes its containing block?
Which edge of a typical positioned block is the reference?
A 200px reference has insets 20px and 30px, auto width, no edges. Width?
Why avoid absolute positioning for main reading flow?