z-index Not Working with Fixed Positioning: Unraveling the Reason
Fixed positioning is a powerful tool for creating elements that remain in place on the screen regardless of scrolling. However, it can sometimes interfere with the z-index property, which controls the stacking order of elements.
To illustrate, consider the following code snippet:
#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 you would expect, the #over element should appear above the #under element since it has a higher z-index. However, in this scenario, #under still overlays #over. Why is this happening?
The answer lies in the default positioning of #over. By default, elements have static positioning, which means they occupy their natural position in the document flow. Fixed positioning elements, on the other hand, are removed from the normal flow and placed at specific coordinates relative to the page'sviewport.
In this case, the fixed position of #under takes it out of the normal flow, and therefore, its z-index becomes irrelevant to elements with static positioning. To make #under appear behind #over, we need to set the positioning of #over to relative. This will place #over in the document flow but allow it to shift its position according to its specified z-index.
Here's the fixed code snippet:
#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; }
Now, the #under element appears underneath #over as expected. Remember, for z-index to work properly, elements must be either absolutely or relatively positioned.
The above is the detailed content of Why Doesn't z-index Work with Fixed Positioning Elements?. For more information, please follow other related articles on the PHP Chinese website!