z-index Not Functioning with Fixed Positioning
In page layout, z-index determines the stacking order of elements on a web page, with higher values appearing on top. However, when an element is positioned fixed, seemingly counter to intuition, it can be difficult to place it behind a statically positioned element using z-index.
Example
Consider the following HTML and CSS code:
<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; }
As evident in the example, despite the higher z-index value assigned to #over, the fixed positioned element #under remains on top.
Explanation
The confounding behavior arises from the inherent differences between static and fixed positioning.
In this context, z-index only determines the stacking order of fixed elements relative to other fixed elements.
Solution
To rectify this issue, add position: relative to the statically positioned element. This creates a new stacking context for #over, allowing z-index to determine its position relative to the newly created context:
#over { width: 600px; z-index: 10; position: relative; } #under { position: fixed; top: 14px; width: 415px; left: 53px; border: 1px solid; height: 10%; background: #f0f; z-index: 1; }
The above is the detailed content of Why Doesn't Z-Index Work as Expected with Fixed Positioning?. For more information, please follow other related articles on the PHP Chinese website!