DEV Community

Cover image for Stacking elements
Sarmun Bustillo
Sarmun Bustillo

Posted on • Updated on

Stacking elements

With modern CSS is very easy to stack elements on top of each other, without much code and can easily be extended with more functionality.

CSS Grid

With CSS Grid we can create customizable grids and assign its items to specific rows and columns. We will take advantage of this to stack our elements.

Let's the following cards as an example:

Unstacked Cards

First, we make the card's container a grid container

.cards {
    display: grid;
}
Enter fullscreen mode Exit fullscreen mode

Next, we explicitly set all the cards into the same column and the row.

.card {
    grid-row: 1;
    grid-column: 1;
}
Enter fullscreen mode Exit fullscreen mode

And guess what, that is it!

Buuuuuut! let me show you with something really simple how easy is to add extra styling.

A bit of offset

So the user can see that the cards are stacked up, let's add a bit of offset. In this example we will go the difficult route, we dont know how many elements (cards) are to be stacked up. So we cant just use CSS, we need to add a bit of JavaScript to dynamically add the offset.

Let's update our card's CSS

.card {
    grid-row: 1;
    grid-column: 1;

    // new lines
  position: relative;
  top:  var(--_card-offset);
}
Enter fullscreen mode Exit fullscreen mode

And With JavaScript we will update our CSS var.

const cards = document.querySelectorAll(".card");
const OFFSET_VALUE: 30;

cards.forEach((card, i) => {
  card.style.setProperty(`--_card-offset`, `${OFFSET_VALUE * i}px`);
})
Enter fullscreen mode Exit fullscreen mode

In a nutshell, each card will be 30px lower than the one before.

Now you can for example set the card's z-index to a higher value whenever it gets hovered so it comes to the front.

.card:hover {
    z-index: 2;
}
Enter fullscreen mode Exit fullscreen mode

Following this same pattern it is very easy to exented the styles and functionality of our stacking elements.

Thank you!

Demo

My Twitter

Checkout my blog

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Great article, keep the good work! Liked and followed! 🚀

Collapse
 
sarmunbustillo profile image
Sarmun Bustillo

Thank you!