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:
First, we make the card's container a grid container
.cards {
display: grid;
}
Next, we explicitly set all the cards into the same column and the row.
.card {
grid-row: 1;
grid-column: 1;
}
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);
}
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`);
})
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;
}
Following this same pattern it is very easy to exented the styles and functionality of our stacking elements.
Thank you!
Top comments (2)
Great article, keep the good work! Liked and followed! 🚀
Thank you!