Positioning is how you break the default 'top-to-bottom' gravity of HTML. It allows you to create complex overlaps, sticky interfaces, and viewport-pinned elements that provide a premium user experience.
1The Anchor Logic
Positioning isn't just about moving elements; it's about defining their 'reference point'.
- →Static: The default. Follows the flow of the document.
- →Relative: Positions itself relative to its own original spot.
- →Absolute: The most powerful. It ignores siblings and looks up the DOM tree for the nearest parent with any position OTHER than static. If it finds none, it anchors to the
<body>. Always remember to setposition: relativeon a parent to 'trap' an absolute child.
2The Stacking Context
When elements overlap, CSS needs a way to decide what goes on top.
- →z-index: A numerical value representing depth. High numbers are 'closer' to the viewer.
- →Important Rule:
z-indexONLY works on elements that are positioned (relative,absolute,fixed, orsticky). If an element isstatic, z-index is ignored. - →Stacking Contexts: Certain properties (like
opacity < 1ortransform) can create 'mini-worlds' where z-index values only compete with other elements inside that same parent.
