Definition:
When you add an element to a webpage, sometimes you want it to appear above or behind other elements.
This is called layering and is set based on your design needs.
The z-index property is then used.
Z-index helps prevent unwanted overlapping between elements on your webpage.
For example, if you want to place two or three divs next to each other, the z-index helps prevent overlapping.
Before using z-index, make sure that the element’s position property is set to relative, absolute, fixed, or sticky—only then will the z-index work.
It also follows the rule of the z-axis.
Syntax:
selector {
position: relative; /* or absolute, fixed, sticky */
z-index: 2;
}
Example:
HTML:
<div class="box1">Box 1</div>
<div class="box2">Box 2</div>
/* CSS */
.box1 {
position: absolute;
top: 50px;
left: 50px;
background: red;
z-index: 1;
}
.box2 {
position: absolute;
top: 70px;
left: 70px;
background: blue;
z-index: 2;
}
Output:
- Red Box (Box 1) appears behind.
- Blue Box (Box 2) appears in front.
- Simple logic: Bigger z-index → Top position on screen.
Visual Output:
Box 1
Box 2
Parameter — Description
- Position → When you want to move or place an element properly, you must set its position (like relative, absolute, fixed, or sticky). Without this, z-index won’t work.
- Z-index → It decides which element appears on top and which goes behind when elements overlap.
The higher the z-index value, the closer to your eyes that element comes — like stacking cards. - Opacity → If you set opacity less than 1 (like 0.5 or 0.8), it creates a new layer and can affect how z-index works.
- Transform → When you use transform (like rotate, scale) on an element, it makes a new layer on its own.
- Filter → When you add effects like blur or brightness to an element using a filter, it also creates a new layer.
- Perspective → It’s used for 3D effects. When you apply it, it adds a new layer on top.
- Will-change → This tells the browser in advance that something (like transform or opacity) will change, so it gets the element ready with a separate layer. This makes the animation or effect smoother and faster.
- Contain → When you want an element to behave on its own — like its size, style, or layout shouldn’t affect others — you use contain. It puts the element in its layer.
- Display → It controls how an element appears on the webpage — like in a block line, inline, flex layout, or even a grid.
Note: When you use the display property, it doesn’t create a new layer. - HTML DOM Order → If two elements have the same z-index, then the one that is written later in the HTML file will appear on top. That means: Later written element overlaps the earlier ones when z-index values are the same.
