Sub topic 2
Containing Blocks and Positioned Ancestors
Assume you know basic HTML, CSS selectors, the box model, and px, %, and rem. This chapter focuses on how CSS chooses the reference box for positioned elements.
Containing blocks and positioned ancestors
A containing block is the rectangle that provides the reference for an element’s size and offsets. For an absolutely positioned element, the containing block is usually the padding box of its nearest ancestor whose position is not static.
The ancestor does not need to be absolute. relative, absolute, fixed, and sticky all create a positioned ancestor.
<div class="card">
<span class="badge">New</span>
<p>Card content</p>
</div>
<style>
.card {
position: relative;
padding: 2rem;
border: 1px solid #ccc;
}
.badge {
position: absolute;
top: 0;
right: 0;
}
</style>The badge uses the card as its containing block because the card has position: relative. Without that declaration, the badge would search higher in the document for another containing block.
Absolute positioning removes an element from flow
An absolutely positioned element is removed from normal flow. Other elements lay out as if it were not there. Its top, right, bottom, and left offsets then place it inside its containing block.
Use absolute positioning for elements attached to a specific component, such as badges, icons, or decorative layers. Do not use it to arrange the main page structure when Flexbox or Grid expresses that structure better.
Fixed positioning pins to a viewport
A fixed element is removed from flow and normally uses the viewport as its containing block. It stays in the same screen position while the document scrolls.
.help-button {
position: fixed;
right: 1rem;
bottom: 1rem;
}Some properties, such as transform on an ancestor, can create a different containing block for fixed descendants. Check ancestors when a supposedly viewport-pinned element moves with a component.
Sticky positioning scrolls, then sticks
A sticky element behaves like a relatively positioned element until scrolling reaches its inset threshold. It then remains attached to that edge while its containing block continues through the scroll area.
.site-header {
position: sticky;
top: 0;
background: white;
z-index: 1;
}Sticky positioning needs an inset such as top: 0. It can also be limited by an ancestor’s height or disrupted by an unexpected scrolling ancestor.
Exercise
A badge is positioned relative to the page instead of its card. What should you check first?
Show answer
Check whether the card has a non-static position, such as position: relative, and whether another ancestor is unexpectedly establishing the containing block.