CodePark/ questions / Display, positioning & stacking
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Display, positioning & stacking

Explain the position values static, relative, absolute, fixed and sticky, and what a containing block is.

position controls how an element is placed. There are five values:

  • static is the default. The element sits in normal flow, and top, left and z-index have no effect.
  • relative stays in flow, but you can shift it visually from its normal spot. Its original space stays reserved. It also becomes the containing block for absolutely positioned descendants.
  • absolute is removed from flow and placed relative to its containing block.
  • fixed is removed from flow and placed relative to the viewport, the visible browser window. The exception: if an ancestor has a transform, filter or similar property, that ancestor becomes its containing block.
  • sticky acts like relative until scrolling reaches the threshold you set with top or a similar property. Then it sticks inside its nearest scrolling ancestor.

A sticky element only sticks while it stays inside its containing block, usually its parent. When the parent scrolls out of view, the sticky element leaves with it.

The containing block is the box that an element is positioned and sized against. Think of it as the frame that top: 0; left: 0 measure from. For an absolute element, it is the padding box of the nearest ancestor whose position is not static. The padding box is the area inside the border, padding included. If there is no such ancestor, it is the initial containing block, a box the size of the viewport at the top of the page.

  • relative stays in flow, shifts visually, and becomes the anchor for absolute children.
  • absolute leaves the flow and is placed against the nearest positioned ancestor.
  • fixed is placed against the viewport, unless an ancestor has transform or filter.
  • sticky acts like relative until a threshold. It needs top or bottom and a scroll container.
  • A sticky element never leaves its containing block, usually its parent.