z-index
is a CSS property that controls the stacking order of elements on a webpage along the z-axis (the imaginary line coming out of your screen). In simpler terms, z-index
determines which elements are in front of or behind other elements when they overlap.
-
Use z-index to control overlapping elements.
-
Higher z-index = closer to the viewer.
-
If no z-index is specified, elements are stacked in the order they appear in the HTML (from bottom to top).
-
Works only on positioned elements (relative, absolute, fixed, sticky).
-
Important for elements that need to always be on top, like modals, menu dropdowns, or sticky headers/footers.
-
Example:
<div style="position: absolute; left: 50px; top: 50px; width: 100px; height: 100px; background-color: red; z-index: 1;"></div>
<div style="position: absolute; left: 70px; top: 70px; width: 100px; height: 100px; background-color: blue; z-index: 2;"></div>
→ Blue box appears on top of red box because it has higher z-index. If no z-index is specified, the blue box still appears on top because it is listed second in the HTML and both boxes have the same stacking context.