CSS
Create Overlapping Elements with CSS Grid
Master the technique of layering elements using CSS Grid by assigning multiple items to the same grid area, perfect for image captions or complex overlays.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Grid Overlapping</title>
<style>
body {
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f4f4f4;
margin: 0;
}
.grid-overlay-container {
display: grid;
width: 400px;
height: 300px;
position: relative; /* For z-index to work reliably across siblings, if needed */
border: 2px solid #555;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.grid-overlay-container > * {
/* Place all children in the same grid area */
grid-area: 1 / 1 / -1 / -1;
/* Shorthand for grid-row-start / grid-column-start / grid-row-end / grid-column-end */
/* 1 / 1 / -1 / -1 means start at row 1, column 1 and span to the last row/column line */
}
.background-image {
width: 100%;
height: 100%;
object-fit: cover;
z-index: 1; /* Ensure image is behind text */
}
.overlay-text {
background-color: rgba(0, 0, 0, 0.6);
color: white;
padding: 15px;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
font-size: 1.5em;
font-weight: bold;
z-index: 2; /* Ensure text is above image */
pointer-events: none; /* Allows clicks to pass through to elements beneath */
}
.overlay-text span {
max-width: 80%;
}
</style>
</head>
<body>
<div class="grid-overlay-container">
<img src="https://via.placeholder.com/400x300/60a5fa/ffffff?text=Background+Image" alt="Placeholder Image" class="background-image">
<div class="overlay-text">
<span>Beautiful Overlay Text with CSS Grid</span>
</div>
</div>
</body>
</html>
How it works: This snippet demonstrates how to create overlapping elements using CSS Grid. By assigning multiple grid items to the exact same grid area (e.g., `grid-area: 1 / 1 / -1 / -1`), they will stack on top of each other. The stacking order is then controlled by the `z-index` property, allowing you to specify which element appears on top. This technique is highly effective for common design patterns like placing text captions over images, creating watermarks, or building complex layered UI components, offering more control than absolute positioning in many scenarios.