Entry 06

Stack layers with grid

Use it whenever things sit on top of each other, such as text over an image, a badge on a card, or two icons that swap. It replaces position: absolute with its offsets, sizes and transforms.

Open
Change the width. Each stack keeps the size of its largest layer and the badge stays in its corner.
Code CSS · 5 lines
.stack { display: grid; }
.stack > * { grid-area: 1 / 1; }

.stack > .title { place-self: center; }
.stack > .badge { place-self: start end; }
Why it works, the rules and the credits 3 reasons · 2 rules · credits

Why it works

  1. Every child goes into the same grid cell, so they overlap.
  2. The layers stay in flow. The container takes the size of its largest layer, where an absolutely positioned child adds nothing to it.
  3. place-self aligns one layer inside the cell. Without it the layer stretches to fill.

Rules

  1. A layer later in the DOM paints on top. Use z-index only to change that order.
  2. Keep position: absolute for a layer that must not affect the container's size.

Credits

Borrowed from: Ana Tudor, @anatudor on X, 2025-03-29

Docs: MDN: grid-area · MDN: place-self