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.
Code
.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
Why it works
- Every child goes into the same grid cell, so they overlap.
- The layers stay in flow. The container takes the size of its largest layer, where an absolutely positioned child adds nothing to it.
place-selfaligns one layer inside the cell. Without it the layer stretches to fill.
Rules
- A layer later in the DOM paints on top. Use
z-indexonly to change that order. - Keep
position: absolutefor 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