Home > Web Front-end > CSS Tutorial > Why Doesn't z-index Work with Fixed Positioning Elements?

Why Doesn't z-index Work with Fixed Positioning Elements?

Patricia Arquette
Release: 2025-01-03 07:18:42
Original
774 people have browsed it

Why Doesn't z-index Work with Fixed Positioning Elements?

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template