Use CSS Grid to stack items.

Published on March 27, 2024
Written by Victor Cobos

Skip position: absolute; for overlapping items. Use display: grid; and then position them in the same column + row.
🎩✨ Grid respects content size, a neat trick lost with absolute positioning.

Demo Screenshot

<div class="grid">
    <div class="item item--1"></div>
    <div class="item item--2"></div>
    <div class="item item--3"></div>
</div>

<style>
    .grid {
        display: grid;
    }

    .item {
        grid-row: 1;
        grid-column: 1;
    }

    .item--1 {
        transform: translate(-2rem, -2rem);
    }

    .item--2 {
        transform: translate(2rem, 2rem);
    }
</style>

Codepen demo

Alternatively, the shorthand method grid-area property to achieve the same result with more concise syntax. By setting grid-area: 1 / 1; on each item you wish to stack. Since the end lines for both rows and columns are not specified, they default to auto, which means the item will span one row, and one column from its starting position.

If you prefer to use TailwindCSS, that's no problem:

<div class="grid *:col-start-1 *:row-start-1">
    <div class="-translate-x-8 -translate-y-8"></div>
    <div class="translate-x-8 translate-y-8"></div>
    <div></div>
</div>

TailwindCSS demo

Subscribe to get future articles via the RSS feed .