Skip to content

Courses / CSS3 Mastery: Beginner to Advanced / Display, Positioning, Stacking Contexts and Z-Index

2,087 people viewed this

Display, Positioning, Stacking Contexts and Z-Index

Display, Positioning and Stacking

Learning Objectives

  • Understand block, inline and inline-block formatting.
  • Use relative, absolute, fixed and sticky positioning.
  • Understand containing blocks.
  • Understand stacking contexts and z-index.

1. Display Values

.block { display: block; }
.inline { display: inline; }
.inline-box { display: inline-block; }
.hidden { display: none; }

Block boxes normally begin on a new line in ordinary flow and can use width and height. Inline boxes participate in inline formatting and do not behave like block boxes for dimensions. Inline-block participates inline while supporting box dimensions.

2. Position: Static and Relative

.normal { position: static; }
.card { position: relative; top: 5px; }

Static is the default position. Relative positioning offsets an element from its normal-flow position while preserving its original layout space.

3. Absolute Positioning

.card { position: relative; }
.badge {
  position: absolute;
  top: 10px;
  right: 10px;
}

An absolutely positioned element is removed from normal flow. Its containing block is often established by the nearest ancestor with a suitable positioning property, although transforms and other properties can also establish containing blocks.

4. Fixed Positioning

.back-to-top {
  position: fixed;
  right: 20px;
  bottom: 20px;
}

Fixed positioning commonly anchors an element to the viewport. Certain ancestor properties can instead establish the containing block for fixed-position descendants.

5. Sticky Positioning

.sidebar-title {
  position: sticky;
  top: 0;
}

Sticky positioning behaves like relative positioning until a scroll threshold is reached within the relevant scrolling container. It requires an appropriate inset and may be affected by ancestor overflow and available space.

6. Z-Index and Stacking Contexts

.modal-backdrop {
  position: fixed;
  inset: 0;
  z-index: 100;
}
.modal {
  position: fixed;
  inset: 10% 10%;
  z-index: 101;
}

z-index controls stacking in contexts where it applies. A stacking context is an isolated stacking group. It can be created by properties such as positioned elements with a non-auto z-index, opacity below 1, transforms, and certain containment or isolation settings.

A child with a huge z-index cannot necessarily appear above elements outside its parent's stacking context. Compare the ancestor contexts when debugging overlays.

7. inset Shorthand

.panel {
  position: absolute;
  inset: 0;
}

Rate this course

No ratings yet — yours can be the first.

Stars show on this course. Your written note stays private.

Your stars