A z-index is a CSS property that controls overlapping HTML elements’ vertical stacking order, which appears closer to the viewer.
Elements with a higher index are placed on top of those with a lower one. Z-index works on most positioned elements, like absolute, relative, and fixed, but not static. The position property helps manipulate an element’s location.
Position Property and Z-index
Several position properties determine which element positioning method a web designer will use. Elements are positioned using the top, bottom, right, and left properties. However, the properties will not work unless the position property is set. Properties also work differently depending on the position value.
There are six position values: absolute, static, relative, fixed, inherit, and sticky. As mentioned, the z-index works with absolute, relative, fixed, sticky, and inherit positions.
- Absolute: The element is extracted from the document’s flow, and other elements behave as if it isn’t there and all the other positional properties will affect it.
- Relative: An element’s original position stays in the document flow; however, the left/right/top/bottom/z-index will now work. The positional properties “nudge” the element from the original position in that direction.
- Fixed: The element is placed relative to a user’s viewport or actual browser window and is not affected by scrolling.
- Sticky: The element value is treated as relative until the viewport’s scroll location reaches a specified threshold. At this point, the element takes a fixed position where it is told to stick.
- Inherit: The position value doesn’t cascade, so it can be used to force it to do so and inherit the positioning value from its parent.
Why Use the Z-index?
Elements can overlap for several reasons, such as when relative positioning nudges it, covering something else; a negative margin has pulled the element over another, or absolutely positioned elements overlap.
Without a z-index value, elements stack in the order that they occur in the DOM (the lowest one down at the same hierarchy level that appears on top). Elements with non-static positioning always appear on top of default static positioning. Also, nesting plays a significant role. For example, if element B sits above element A, a child element of element A can never be higher than element B.