CSS
Overlay Text or Badges on an Image Using CSS Grid
Create dynamic overlays like captions, badges, or buttons on top of images or cards efficiently using CSS Grid for precise positioning and stacking.
<div class="grid-card">
<img src="https://via.placeholder.com/400x250/87CEEB/FFFFFF?text=Product+Image" alt="Product" class="card-image">
<div class="card-caption">Stunning Landscape View</div>
<span class="card-badge">New!</span>
</div>
<style>
.grid-card {
display: grid;
grid-template-areas: "stack"; /* All children will occupy the same grid area */
position: relative; /* Useful for pseudo-elements or specific z-index contexts */
width: 400px; /* Example fixed width */
overflow: hidden; /* Clip content that extends beyond the card */
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
margin: 20px;
}
.card-image,
.card-caption,
.card-badge {
grid-area: stack; /* Assign all to the same grid area */
}
.card-image {
width: 100%;
height: auto;
display: block; /* Remove extra space below image */
}
.card-caption {
align-self: end; /* Align to the bottom of the grid area */
justify-self: start; /* Align to the start (left) */
background-color: rgba(0, 0, 0, 0.6);
color: white;
padding: 10px;
width: 100%; /* Ensure caption spans full width */
box-sizing: border-box;
z-index: 1; /* Ensure caption is above the image */
}
.card-badge {
align-self: start; /* Align to the top */
justify-self: end; /* Align to the end (right) */
background-color: #ff5722;
color: white;
padding: 5px 10px;
border-radius: 0 0 0 8px; /* Rounded bottom-left only */
font-size: 0.8em;
font-weight: bold;
z-index: 2; /* Ensure badge is above caption */
}
</style>
How it works: This snippet leverages CSS Grid to easily overlay elements, such as a caption and a badge, on top of an image within a card. By assigning all child elements (`.card-image`, `.card-caption`, `.card-badge`) to the same named grid area ("stack"), they automatically stack on top of each other. Within this shared grid area, properties like `align-self` and `justify-self` are used to precisely position each overlay (e.g., caption at the bottom-left, badge at the top-right) without needing `position: absolute`. `z-index` is used to control the stacking order of the overlays.