How to Overlay One Div Over Another
Creating an overlay effect for two <div> elements can be easily done with CSS. This can be done with the combination of the CSS position and z-index properties. The z-index of an element defines its order inside a stacking context. In our examples, we’ll use the “absolute” and “relative” values of the position property and add the z-index property to specify the stacking order for the positioned elements.
So, let’s start!
Create HTML
- Use a <div> element with the class named “container”.
- Add two other <div> elements within the first one. Add classes to them as well.
<div class="container">
<div class="box"></div>
<div class="box overlay"></div>
</div>
Add CSS
- Specify the width and height of the "container" class. Set the position to "relative" and add the margin property.
- Set both the width and height of the "box" class to "100%". Specify the position with the "absolute" value. Add the top and left properties. Also, specify the background and opacity of the "box" class.
- Style the "overlay" class by using the z-index, margin and background properties.
.container {
width: 150px;
height: 150px;
position: relative;
margin: 30px;
}
.box {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
opacity: 0.7;
background: #0057e3;
}
.overlay {
z-index: 9;
margin: 30px;
background: #009938;
}
Now, we can bring together the parts of our code.
Example of overlaying one <div> over another:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.container {
width: 150px;
height: 150px;
position: relative;
margin: 30px;
}
.box {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
opacity: 0.7;
background: #0057e3;
}
.overlay {
z-index: 9;
margin: 30px;
background: #009938;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
<div class="box overlay"></div>
</div>
</body>
</html>
Result
Let’s see another example where we use a bit more CSS. Here, we add some hovering effects using the CSS :hover pseudo-class.
Example of overlaying one <div> over another with hovering effects:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.container {
position: absolute;
height: 250px;
width: 400px;
background-color: #7d807e;
}
.box1 {
color: #fff;
padding-top: 60px;
padding-left: 50px;
font-size: 50px;
font-weight: bold;
}
.box2 {
padding-left: 50px;
}
.box1:hover {
z-index: -1;
opacity: 0.5;
font-size: 30px;
text-align: center;
transform-style: all;
transition-duration: 2s;
}
.box2:hover {
z-index: -1;
opacity: 0.3;
font-size: 40px;
text-align: center;
transform-style: all;
transition-duration: 2s;
}
</style>
</head>
<body>
<div class="container">
<div class="box1">W3Docs</div>
<div class="box2">Learn programming</div>
</div>
</body>
</html>