Home >Web Front-end >CSS Tutorial >Why Does Fixed Positioning Break Z-Index Ordering?
Understand the Z-Index Paradox with Fixed Positioning
When dealing with HTML elements, the z-index property controls the stacking order, determining which element appears above or below others on the page. However, an unexpected behavior occurs when using z-index with elements positioned fixed and static.
Consider the following code snippet:
#over { width: 600px; z-index: 10; } #under { position: fixed; top: 5px; width: 420px; left: 20px; z-index: 1; }
You would expect the element with #over to be displayed behind #under since it has a higher z-index value. However, the fixed element (#under) will stubbornly overlay #over, ignoring its supposed lower priority.
This is because fixed positioning removes an element from the normal document flow. It positions the element based on the viewport, essentially creating a separate layer on top. As a result, the z-index of fixed elements doesn't interact with the z-index of non-fixed elements.
To rectify this issue and allow #over to appear behind #under, add position: relative; to #over:
#over { width: 600px; z-index: 10; position: relative; }
This small adjustment establishes a new local stacking context within #over, enabling its z-index to influence elements within that context. Now, #under will display correctly behind #over, respecting the intended stacking order.
Remember, fixed positioning is a powerful tool for creating absolute positioning on the page, but it comes with limitations when interacting with z-index in certain scenarios. By applying the position: relative trick, you can regain control over the stacking order and achieve your desired layering effects.
The above is the detailed content of Why Does Fixed Positioning Break Z-Index Ordering?. For more information, please follow other related articles on the PHP Chinese website!