CSS Layers and Opacity
This tutorial demonstrates how to use z-index
for layering elements and opacity
to create transparency effects. Positioning elements with absolute
ensures they can overlap.
1. HTML Structure
The HTML is simple, containing three overlapping <div>
elements:
<div class="box1">
<h1>Hello</h1>
</div>
<div class="box2"></div>
<div class="box3"></div>
2. CSS Explanation
The CSS positions the boxes using absolute
positioning and assigns different z-index
and opacity
values to create a layered and transparent effect:
.box1 {
width: 200px;
height: 200px;
background-color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */
position: absolute;
left: 100px;
top: 100px;
z-index: 100; /* Topmost layer */
opacity: 0.5; /* Makes it partially see-through */
}
.box2 {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
left: 150px;
top: 150px;
z-index: 50; /* Sits below box1 */
}
.box3 {
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
left: 200px;
top: 200px;
z-index: 1; /* Bottommost layer */
}
3. Key Concepts
z-index
: Determines the stack order of elements. Higher values appear above lower values. Elements with the samez-index
follow the DOM order.opacity
: Controls the transparency of an element, with values ranging from0
(completely transparent) to1
(completely opaque).position: absolute
: Positions elements relative to the nearest positioned ancestor or the document body if none exists.background-color
withrgba
: Adds transparency to the background color.
4. Complete Code
Here’s the full code for this tutorial:
HTML
<IDOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="layers.css">
<title>Layers and opacity</title>
</head>
<body>
<div class="box1">
<h1>Hello</h1>
</div>
<div class="box2"></div>
<div class="box3"></div>
</body>
</html>
Run Code
CSS
.box1 {
width: 200px;
height: 200px;
background-color: rgb(255, 0, 0, 0.5);
position: absolute;
left: 100px;
top: 100px;
z-index: 100;
opacity: 0.5;
}
.box2 {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
left: 150px;
top: 150px;
z-index: 50;
}
.box3 {
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
left: 200px;
top: 200px;
}
Run Code
6. Summary
By using z-index
and opacity
, you can create visually appealing designs with layered effects and transparency. Experiment with different values to better understand their behavior!