DEV Community

Andreas B. Vestergaard
Andreas B. Vestergaard

Posted on

2

CSS Grid vs. Position Absolute for Overlapping Elements

When you need to position elements on top of each other, many developers instinctively reach for position: absolute. While this approach works, it comes with several drawbacks including elements being removed from the document flow, which can cause layout issues and complicate responsive design.

CSS Grid offers a more elegant solution for creating overlapping elements. By placing multiple child elements in the same grid cell, you can achieve the same visual effect while maintaining a more predictable layout system.

Here's a simple implementation:

.parent {
  display: grid;
  grid-template-columns: 1fr;
  grid-auto-rows: min-content;
}

.div1 {
  grid-area: 1 / 1 / 2 / 2;
}

.div2 {
  grid-area: 1 / 1 / 2 / 2;
}
Enter fullscreen mode Exit fullscreen mode

The beauty of this approach is that:

  • All elements remain in the document flow
  • The parent container will properly size itself based on its content
  • It's easier to center content or align it consistently
  • You gain all the responsive benefits of CSS Grid
  • Z-index still works as expected to control stacking order

This technique is particularly useful for card overlays, image captions, or any UI component where elements need to be stacked precisely.

For more complex overlapping patterns, you can combine this with the z-index property to control which elements appear on top, just as you would with absolutely positioned elements.

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

Top comments (1)

Collapse
 
alohci profile image
Nicholas Stimpson

One aspect you might have mentioned is how to use them to do partial overlaps, like this:

Dev Diairies image

User Feedback & The Pivot That Saved The Project ↪️

We’re following the journey of a dev team building on the Stellar Network as they go from hackathon idea to funded startup, testing their product in the real world and adapting as they go.

Watch full video 🎥

👋 Kindness is contagious

Embark on this engaging article, highly regarded by the DEV Community. Whether you're a newcomer or a seasoned pro, your contributions help us grow together.

A heartfelt "thank you" can make someone’s day—drop your kudos below!

On DEV, sharing insights ignites innovation and strengthens our bonds. If this post resonated with you, a quick note of appreciation goes a long way.

Get Started