Positioning
CSS Z-Index
Controlling Stacking Order
CSS z-index controls element stacking, with stacking context rules.
Introduction to CSS Z-Index
The z-index property in CSS controls the vertical stacking order of elements that overlap. It is pivotal in determining which elements appear on top of others on a webpage. Z-index only affects elements whose position is set to something other than the default static positioning.
Basic Usage of Z-Index
The z-index property can be assigned to any positioned element (elements with position values of relative
, absolute
, fixed
, or sticky
). A higher z-index value means the element will appear on top of elements with lower z-index values.
Understanding Stacking Context
A stacking context is a 3D conceptualization of HTML elements along an imaginary z-axis relative to the user viewing the webpage. This context is formed by elements that meet specific criteria, such as having a position value other than static and a z-index value other than auto. Each stacking context is isolated from its siblings, meaning that z-index values are only considered within the same context.
Creating a New Stacking Context
New stacking contexts can be formed not only by setting a z-index but also by CSS properties such as opacity
, transform
, filter
, and flex
container with a z-index. Elements that create a new stacking context will stack their children independently from the rest of the document.
Practical Example of Z-Index
Consider a scenario with multiple overlapping elements. Using z-index, you can control their rendering order:
In this example, the red box is on top of the blue box due to its higher z-index value.
Common Pitfalls and Tips
- Remember that z-index only works on positioned elements (not
static
). - Check for parent elements that might have created a new stacking context affecting the z-index behavior.
- Use z-index values sparingly and document them well in your CSS to avoid confusion.
Positioning
- Previous
- Position Sticky
- Next
- Media Queries