The z-index property in CSS controls the stacking order of elements along the z-axis — the imaginary line perpendicular to the screen (front-to-back). This determines which elements appear in front of others when they overlap.
Key points to know:
z-index value means the element will appear in front of elements with lower values.z-index is auto, which follows the element's natural HTML order.z-index only works on elements with a positioning context (position: relative, absolute, fixed, or sticky).z-index, their stacking order depends on their position in the DOM (elements later in the HTML appear on top).Important: z-index only works on elements with a position of relative, absolute, fixed, or sticky.
.box1 {
position: absolute;
z-index: 1;
}
.box2 {
position: absolute;
z-index: 2;
}z-index: 10 – appears above elements with lower indexz-index: -1 – pushes element behind othersz-index: auto – default stacking contextIf no z-index is set, elements are layered based on their HTML order and positioning. Positioned elements are stacked above static ones by default.
Use z-index to stack tooltips, modals, navigation bars, dropdowns, etc.
.modal {
position: fixed;
top: 0;
left: 0;
z-index: 999;
}Create three overlapping boxes with different z-index values:
<div style={{
position: "absolute",
top: "50px",
left: "50px",
width: "150px",
height: "150px",
backgroundColor: "lightblue",
zIndex: 1
}}>
Box 1 (z-index: 1)
</div>
<div style={{
position: "absolute",
top: "100px",
left: "100px",
width: "150px",
height: "150px",
backgroundColor: "salmon",
zIndex: 3
}}>
Box 2 (z-index: 3)
</div>
<div style={{
position: "absolute",
top: "75px",
left: "75px",
width: "150px",
height: "150px",
backgroundColor: "palegreen",
zIndex: 2
}}>
Box 3 (z-index: 2)
</div>You can copy and paste this code in your IDE to run!
Ask the AI if you need help understanding or want to dive deeper in any topic