To overlay one <div>
over another in CSS, use positioning and z-index. Here are three common methods:
1. Using position: absolute
(Most Common)
<div class="container">
<div class="base-div">Base Div</div>
<div class="overlay-div">Overlay Div</div>
</div>
.container {
position: relative; /* Required for absolute positioning context */
width: 300px;
height: 200px;
}
.base-div {
width: 100%;
height: 100%;
background: lightblue;
}
.overlay-div {
position: absolute;
top: 20px; /* Position relative to container */
left: 20px;
width: 50%;
height: 50%;
background: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
z-index: 1; /* Ensures overlay is above base div */
}
2. Using CSS Grid
.container {
display: grid;
width: 300px;
height: 200px;
}
.base-div, .overlay-div {
grid-area: 1 / 1; /* Place both divs in the same grid cell */
}
.overlay-div {
align-self: start; /* Adjust position */
justify-self: start;
z-index: 1;
background: rgba(0, 255, 0, 0.5);
}
3. Using Flexbox
.container {
display: flex;
width: 300px;
height: 200px;
}
.base-div {
width: 100%;
height: 100%;
background: lightblue;
}
.overlay-div {
position: absolute; /* Still use absolute positioning */
top: 20px;
left: 20px;
z-index: 1;
}
Key Concepts
position: relative
on the container creates a positioning context for child elements.position: absolute
removes the overlay from the normal document flow.z-index
controls stacking order (higher values appear on top).- Transparency is achieved with
rgba()
oropacity
.
Common Issues & Fixes
Problem | Solution |
---|---|
Overlay not appearing | Ensure z-index is higher than the base div’s. |
Overlay positioned incorrectly | Check parent’s position: relative . |
Overlay overflowing container | Adjust top , left , right , or bottom values. |