Home >Web Front-end >CSS Tutorial >Why Doesn't z-index Affect Fixed-Positioned Elements?
Element with Fixed Positioning Not Affected by z-index
In CSS, the z-index property controls the stacking order of elements on the page, where higher values move elements to the forefront. However, sometimes fixed positioned elements seem immune to z-index changes.
This behavior is caused by the default static positioning of fixed elements. When an element with fixed positioning is placed within another element with default positioning, it creates a stacking context within that element. Within this context, the fixed element is layered above any other elements, regardless of their z-index.
To resolve this issue, you can add relative positioning to the parent element. This establishes a new stacking context within the parent, allowing the z-index of the fixed element to take effect.
Example:
Consider the following HTML and CSS:
<div>
#over { width: 600px; z-index: 10; } #under { position: fixed; top: 5px; width: 420px; left: 20px; border: 1px solid; height: 10%; background: #fff; z-index: 1; }
In this case, the #under element will remain on top of the #over element, even though the latter has a higher z-index. To fix this, add relative positioning to the #over element:
#over { width: 600px; z-index: 10; position: relative; }
Now, the z-index of the #under element will work as expected, placing it behind the #over element.
The above is the detailed content of Why Doesn't z-index Affect Fixed-Positioned Elements?. For more information, please follow other related articles on the PHP Chinese website!