Stacking Elements with Grid

3rd March 2020 3 min read

Stacking an element on top of another used to be a task commonly solved using position: absolute followed by forgetting to add position: relative to the parent and seeing the element in question appear off in a totally unwanted direction.
However nowadays I utilise the power of display: grid.

We can now achieve stacking, demo'd above in the form the the "Glassmorphism" trend, by making all the child elements of a grid span the whole area. The best part is we can do it in two just a few lines of css...

.grid {
    display: grid
}

.grid.stack > * {
    grid-column: 1;
    grid-row: 1;
}

I like this method for a few reasons. One is that as this problem feels like a layout problem and with that in mind it feel more intuitive to use a modern and common layout tool.
Another plus for this method is that we can now easily stack multiple elements on top of one another by adding multiple children inside an element with the classes grid and stack. If however you are not a fan of the * selector, as there can be some performance concerns, you can easily reach for the following CSS

.grid {
    display: grid
}

.stack {
    grid-column: 1;
    grid-row: 1;
}

And lastly when stacking elements don't forget to add the relevant z-index.

ADDED BONUS: My Tailwind config for this feature

plugins: [
  plugin(function({ addUtilities }) {
    const newUtilities = {
      '.stack': {
        gridColumn: '1',
        gridRow: '1'
      }
    }

    addUtilities(newUtilities, {
      variants: ['responsive', 'hover'],
    });
  })
],

Made with in Brighton • by Mark Ryan