Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Overlap Elements with CSS
To overlap elements in CSS, you need to control their stacking order using positioning and the z-index property. Elements with higher z-index values appear in front of elements with lower values.
Syntax
selector {
position: relative | absolute | fixed;
z-index: integer;
}
Key Properties for Overlapping
| Property | Description |
|---|---|
position |
Must be relative, absolute, or fixed for z-index to work |
z-index |
Controls stacking order (higher values appear on top) |
top, left, right, bottom |
Controls precise positioning of overlapping elements |
Example: Image Behind Text
The following example places an image behind text using negative z-index −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
width: 300px;
height: 250px;
}
.background-image {
position: absolute;
left: 0;
top: 0;
z-index: -1;
width: 100%;
height: 100%;
object-fit: cover;
}
.overlay-text {
position: relative;
z-index: 1;
background-color: rgba(255, 255, 255, 0.8);
padding: 20px;
margin: 50px;
text-align: center;
font-size: 18px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<img src="/assets/images/sample.jpg" alt="Background" class="background-image">
<div class="overlay-text">This text appears over the image</div>
</div>
</body>
</html>
A container with a background image and semi-transparent white text box overlaying it. The text "This text appears over the image" is clearly visible on top of the background image.
Example: Multiple Overlapping Layers
The following example demonstrates multiple elements with different z-index values −
<!DOCTYPE html>
<html>
<head>
<style>
.overlap-container {
position: relative;
width: 200px;
height: 200px;
margin: 50px;
}
.layer {
position: absolute;
width: 100px;
height: 100px;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
.layer1 {
background-color: #ff6b6b;
top: 0;
left: 0;
z-index: 1;
}
.layer2 {
background-color: #4ecdc4;
top: 30px;
left: 30px;
z-index: 2;
}
.layer3 {
background-color: #45b7d1;
top: 60px;
left: 60px;
z-index: 3;
}
</style>
</head>
<body>
<div class="overlap-container">
<div class="layer layer1">Layer 1</div>
<div class="layer layer2">Layer 2</div>
<div class="layer layer3">Layer 3</div>
</div>
</body>
</html>
Three colored squares overlapping each other in a stair-step pattern. The blue square (Layer 3) appears on top, followed by the teal square (Layer 2), and the red square (Layer 1) at the bottom.
Conclusion
CSS overlapping is achieved using the position and z-index properties. Higher z-index values stack elements on top, while negative values place elements behind others in the normal document flow.
Advertisements
