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.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X