← Back to all snippets
CSS

Overlapping Elements with CSS Grid

Learn to precisely position and overlap elements using CSS Grid, creating unique visual effects and complex layered designs with minimal markup and robust control.

.overlap-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
  grid-template-rows: repeat(3, 1fr);    /* 3 equal rows */
  width: 400px;
  height: 300px;
  border: 2px dashed #ccc;
  overflow: hidden; /* Important if content overflows due to overlap */
  position: relative; /* Establish stacking context for z-index */
}

.item-a,
.item-b {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 1.2em;
  color: white;
  border-radius: 8px;
}

.item-a {
  grid-column: 1 / 3; /* Spans 2 columns */
  grid-row: 1 / 3;    /* Spans 2 rows */
  background-color: rgba(255, 99, 71, 0.7); /* Tomato */
  z-index: 1; /* Place below */
}

.item-b {
  grid-column: 2 / 4; /* Spans 2 columns */
  grid-row: 2 / 4;    /* Spans 2 rows */
  background-color: rgba(60, 179, 113, 0.7); /* MediumSeaGreen */
  z-index: 2; /* Place above */
}
How it works: This snippet demonstrates how to achieve overlapping elements using CSS Grid. By defining a grid on the parent, individual grid items can be explicitly placed over multiple grid cells using `grid-column` and `grid-row` properties. When two items occupy common grid cells, they overlap. The `z-index` property is then used to control their stacking order, allowing precise control over which item appears on top for complex visual designs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs