← Back to all snippets
CSS

Overlapping Elements and Layering with CSS Grid

Create engaging designs by deliberately overlapping elements within a CSS Grid layout, leveraging grid-area and z-index for precise control over layering.

.grid-overlap-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 150px);
  gap: 10px;
  width: 400px;
  height: 300px;
  border: 2px solid #ccc;
  position: relative; /* Important for z-index context */
}

.item-1 {
  grid-column: 1 / 3; /* Spans across both columns */
  grid-row: 1 / 2; /* Occupies the first row */
  background-color: #ffeb3b; /* Yellow */
  z-index: 1;
}

.item-2 {
  grid-column: 1 / 2; /* First column */
  grid-row: 1 / 3; /* Spans both rows */
  background-color: #03a9f4; /* Blue */
  opacity: 0.8;
  z-index: 2;
}

.item-3 {
  grid-column: 2 / 3; /* Second column */
  grid-row: 2 / 3; /* Second row */
  background-color: #4caf50; /* Green */
  z-index: 3;
}

.grid-item {
  padding: 10px;
  border: 1px dashed #666;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #333;
  font-weight: bold;
}
How it works: This snippet demonstrates how to create overlapping elements within a CSS Grid layout, a powerful technique for creative designs. Each `.grid-item` is assigned to specific grid columns and rows using `grid-column` and `grid-row` properties, allowing them to occupy areas that naturally overlap. The `z-index` property then controls the stacking order of these overlapping items, determining which element appears on top. The `position: relative` on the container is crucial to establish a stacking context for `z-index` to work correctly. This approach provides fine-grained control over element placement and layering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs