CSS Properties
CSS z-index Property
Photo Credit to CodeToFun
🙋 Introduction
The z-index
property in CSS controls the vertical stacking order of elements that overlap. When elements overlap, the z-index
value determines which one appears on top.
This property only works on positioned elements (those with a position value other than static).
💡 Syntax
The syntax for the z-index
property is simple and can be applied to any positioned element.
element {
z-index: value;
}
Here, value can be an integer representing the stacking order.
🎛️ Default Value
The default value of the z-index
property is auto, which means the element will use the default stacking order based on its order in the HTML and its parent stacking context.
🏠 Property Values
Value | Description |
---|---|
auto | The element inherits the default stacking order. |
integer | Any integer value, positive or negative. A higher value means the element will be displayed in front of elements with lower values. |
📄 Example
In this example, we will stack three colored boxes using the z-index
property.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS z-index Example</title>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
opacity: 0.7;
}
.box1 {
background-color: red;
top: 50px;
left: 50px;
z-index: 1;
}
.box2 {
background-color: green;
top: 100px;
left: 100px;
z-index: 2;
}
.box3 {
background-color: blue;
top: 150px;
left: 150px;
z-index: 3;
}
</style>
</head>
<body>
<h1>Boxes with Different z-index Values</h1>
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
</body>
</html>
🖥️ Browser Compatibility
The z-index
property is fully supported in all modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. It is also supported in older browsers, making it a reliable property to use for controlling the stacking order of elements.
🎉 Conclusion
The z-index
property is an essential tool for web developers when designing layouts with overlapping elements.
By controlling the stacking order, you can create complex and visually appealing designs. Experiment with different z-index
values to see how they affect the stacking order of elements on your web pages.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (CSS z-index Property), please comment here. I will help you immediately.