Determining the Containing Block for Positioned Elements
In CSS, the containing block of a positioned element determines the reference frame for offsets like top, left, right, and bottom. How the containing block is calculated depends on the element's position value and its ancestors.
Static or Relative – For position: relative or static, the containing block is the same as the parent element's content box.
Absolute – For position: absolute, the containing block is the nearest ancestor that has a position value other than static (relative, absolute, sticky, or fixed). If no such ancestor exists, the initial containing block (usually the <html> element) is used.
Fixed – For position: fixed, the containing block is usually the viewport, ignoring any positioned ancestors.
Sticky – For position: sticky, the containing block is the nearest ancestor that can scroll, and the element sticks within that ancestor's bounds.
Here, the .absolute-box is positioned relative to .container because .container has position: relative. If .container did not have a position set, .absolute-box would be positioned relative to the initial containing block (viewport).
Always give a parent container a position value other than static when you want precise control over absolute child elements.
Understand that fixed elements are relative to the viewport, not ancestors.
Use sticky positioning carefully to respect scrollable ancestor boundaries.
Consider the containing block when combining z-index and layered layouts to avoid unexpected overlaps.
Test layouts across different viewport sizes to ensure offsets behave as expected.