Home > Web Front-end > CSS Tutorial > Why Doesn't Z-Index Work as Expected with Fixed Positioning?

Why Doesn't Z-Index Work as Expected with Fixed Positioning?

Mary-Kate Olsen
Release: 2024-12-23 15:43:11
Original
905 people have browsed it

Why Doesn't Z-Index Work as Expected with Fixed Positioning?

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>
Copy after login
#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 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.

  • Static positioning leaves elements unaffected by z-index, as they lie in the normal flow of the document.
  • Fixed positioning, on the other hand, removes elements from the normal flow and positions them relative to the viewport (the user's screen).

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

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!

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