In both the normal flow and Flexbox layout algorithms, an element's box is placed right after its predecessor in the direction of flow. Such linear flow works well for flat and sequential documents made up of text and figures. In the 1990s, web developers began breaking away from simple documents as they built full-fledged user interfaces like those found in desktop applications. Visual elements in desktop applications don't just appear in sequence. Menus, dialog boxes, and heads-up displays stack on top of other elements on adjacent to other elements. To support the building of complex interfaces, the position
property was added to CSS.
An element's position
property changes how an element's box is anchored against another box on the page. The property can be set to these values:
static
, which means the element's box will be placed according to the layout algorithm used by the parent. This is the default that you've been using up till now. With normal flow, the element is anchored against its predecessor.relative
, which means the element's box will still appear in the normal flow but it will be offset from its normal position.fixed
, which means the element's box will be removed from the normal flow and anchored against the browser's viewport.absolute
, which means the element's box will be removed from the normal flow and anchored against one of its ancestor elements.sticky
, which means the element's box will appear in its normal static position until it starts to scroll out of view, at which point it will be anchored against the scrolling container.The terms are not descriptive, and relative
is the worst offender. All values but static
cause the box to be anchored relative to some box. Consider these alternative names:
relative
→ relative-to-self
fixed
→ relative-to-viewport
absolute
→ relative-to-ancestor
sticky
→ relative-to-scrolling-ancestor
These alternative names aren't legal in CSS. Maybe you can change that.
Using any value besides static
unlocks four other properties that describe how the element's box is offset from its anchor: left
, right
, top
, and bottom
. These properties are assigned values that describe how the element's edge is positioned relative to its anchor's corresponding edge. These values can be lengths or percentages. For example, consider these possible assignments to the left
property:
left: 20px
means that the element's left edge is pushed inward 20 pixels from its anchor's left edgeleft: -20px
means that the element's left edge is pushed outward 20 pixels from its anchor's left edgeleft: 0
means that the element's left edge is perfectly aligned with its anchor's left edgeleft: 100%
means that the element's left edge is pushed inward so that it completely clears the anchor box and sits to its rightBut this stuff will make more sense with a visual demonstration.