Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

I came across Sarah Dresner's article How to Stack Elements in CSS and learned that one could use display: grid; to stack elements. That's right, place elements over each other without a position: absolute! ๐Ÿ˜ฒ

The trick are overlapping grid-area declarations.

Let's say we have the following HTML:

<div class="photoCard">
  <img src="https://.../cutedog.jpg" alt="A cute dog">
  <div class="red">red</div>
  <div class="blue">blue</div>

Then you place the elements using CSS Grid as follows:

.photoCard {
  display: grid;

img { grid-area: 1 / 1 / 4 / 2; }
.red { grid-area: 1 / 1 / 2 / 2; }
.blue { grid-area: 3 / 1 / 4 / 2; }

The CSS above makes the img element span over three rows. Contrary, the .blue and .red element are placed on the first and third row leading them to be stacked on top of the image.

To visualize it, I made a quick #devsheet about it. ๐Ÿ˜Š

Visual demo on stacked elements using CSS Grid

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 4 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles