Home >Web Front-end >CSS Tutorial >Why Does Sticky Positioning Behave Differently Than the MDN Documentation Describes?

Why Does Sticky Positioning Behave Differently Than the MDN Documentation Describes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 06:45:09843browse

Why Does Sticky Positioning Behave Differently Than the MDN Documentation Describes?

Scrutinizing the Discrepancy in Sticky Position Behavior

The MDN documentation portrays sticky positioning as an attribute that transitions elements from relative placement to fixed placement once a defined threshold is surpassed. However, in practice, it behaves differently. This discrepancy stems from a misunderstanding of the order in which these states are implemented.

According to MDN, sticky position elements initially behave like relative position elements until the threshold is exceeded. However, in the context where bottom:0 is specified, the threshold is already surpassed in the initial state. As a result, the element directly enters its fixed placement and remains as such until the element's position exceeds 0px from the bottom of the viewport.

Understanding Sticky Position States

Position:sticky has two distinct states:

  1. Relative State: The element behaves like a relatively positioned object.
  2. Fixed State: The element adheres to a fixed position against the viewport.

The initial state is determined by the element's placement and the defined threshold. In the case of bottom:0, the threshold is immediately surpassed, leading to an initial fixed state. As the viewport scrolls, the element will remain fixed until the distance from the bottom edge becomes greater than 0px. At this point, it reverts to its relative state.

Illustrating the Behavior

Consider the following code snippet:

body {
  height:150vh;
  margin:0;
  display:flex;
  flex-direction:column;
  border:2px solid;
  margin:50px;
}

.b {
  margin-top:auto;
  position:sticky;
  bottom:0;
}

.a {
  position:sticky;
  top:0;
}
<div class="a"> 
  I will start relative then I will be fixed
</div>
<div class="b"> 
  I will start fixed then I will be relative
</div>

Element A, with top:0, will initially behave as relative and transition to fixed when it reaches the top of the viewport. Element B, with bottom:0, will immediately start in a fixed position and transition to relative when the distance from the bottom of the viewport exceeds 0px.

The above is the detailed content of Why Does Sticky Positioning Behave Differently Than the MDN Documentation Describes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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