CSS Grid can be used to stack elements

Published at
Updated at
Reading time
1 min

This post is part of my Today I learned series in which I share all my learnings regarding web development.

I came across the article How to Stack Elements in CSS written by Sarah Dresner and learned that one could use display: grid; to stack element without setting any absolute positioning! ๐Ÿ˜ฒ

The trick is that you can define 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>
</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. ๐Ÿ˜Š

Related Topics

See null comment.