Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Stacking elements on top of each other with CSS grid

Even dough I don't believe the CSS grid was designed especially for stacking elements one on top of each other this can be achieved easily with a combination of grid-area and z-index.

Let's say we want to build the below widget.

This can be described by the following HTML structure:

<div class="card">
    <div class="top">A cat named</div>
    <div class="bottom">TOM</div>
    <img src="http://examples.js-craft.io/tom.png" alt="TOM">
</div> 

If we place it in grid layout of 1 column - 3 rows then we can easily say something like:

.card { display: grid; }
img {  grid-area: 1 / 1 / 4 / 2;  }
.top { grid-area: 1 / 1 / 2 / 2; }
.bottom { grid-area: 3 / 1 / 4 / 2; }
.card div { z-index: 2; }

That's pretty much all that we need to stack elements on top of each other with the CSS grid. Just don't forget to set the z-index prop to the elements you want on top and that the grid-column is using line numbers to place items. Therefore that's the reason why we have lines like img { grid-area: 1 / 1 / 4 / 2; } even if we have just 1 column and 3 rows.

By the way, if you are interested to find out more about CSS grid and other frontend tips you can sign up for my newsletter. You can check out here and here some examples of the js-craft newsletter.

Below you have the full working example:

See the Pen
tom-cat
by JS Craft (@js-craft)
on CodePen.

Home Screencasts Best of Newsletter Search X