Stacking Items With CSS Grid

Published Mar 3, 2024

Use CSS Grid instead of position absolute to stack items on top of each other.

html
<div class="stack">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
css
.stack {
  display: grid;
  place-content: center;

  > * {
    grid-area: 1 / 1;
  }
}

Using the grid-area CSS shorthand property the grid item starts at the first grid line of the grid row (grid-row-start: 1) and the first grid line of the grid column (grid-column-start: 1).

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.

Support

You can subscribe on YouTube, or consider becoming a patron if you want to support my work.

Patreon
Found a mistake?

Every post is a Markdown file so contributing is simple as following the link below and pressing the pencil icon inside GitHub to edit it.

Edit on GitHub