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
Create layers using CSS
To create layers using CSS, you can control the stacking order of elements using the z-index property combined with positioned elements. This allows you to stack elements on top of each other and control which element appears in front.
Syntax
selector {
position: relative | absolute | fixed | sticky;
z-index: integer;
}
How Z-Index Works
The z-index property only works on positioned elements (elements with position other than static). Higher z-index values appear on top of lower values.
| Z-Index Value | Stacking Order |
|---|---|
| Higher numbers (e.g., 3) | Front layer |
| Lower numbers (e.g., 1) | Back layer |
| Negative numbers | Behind normal flow |
Example: Creating Overlapping Layers
The following example creates three colored boxes that overlap each other using different z-index values −
<!DOCTYPE html>
<html>
<head>
<style>
.layer {
width: 200px;
height: 80px;
position: absolute;
color: white;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.red-layer {
background-color: red;
top: 50px;
left: 50px;
z-index: 2;
}
.yellow-layer {
background-color: orange;
top: 80px;
left: 80px;
z-index: 1;
}
.green-layer {
background-color: green;
top: 110px;
left: 110px;
z-index: 3;
}
</style>
</head>
<body>
<div class="layer red-layer">Red (z-index: 2)</div>
<div class="layer yellow-layer">Orange (z-index: 1)</div>
<div class="layer green-layer">Green (z-index: 3)</div>
</body>
</html>
Three overlapping colored boxes appear with the green box on top (z-index: 3), red box in the middle (z-index: 2), and orange box at the bottom (z-index: 1).
Key Points
- Elements must have
positionset to relative, absolute, fixed, or sticky forz-indexto work - Higher
z-indexvalues stack above lower values - Elements without
z-indexhave a default stacking order based on document flow
Conclusion
CSS layers are created using the z-index property on positioned elements. This technique is essential for creating overlays, modals, tooltips, and complex layouts where elements need to stack on top of each other.
