Home > Web Front-end > CSS Tutorial > Why Does `bottom: 0` in Sticky Positioning Act Opposite to Expectations?

Why Does `bottom: 0` in Sticky Positioning Act Opposite to Expectations?

Mary-Kate Olsen
Release: 2024-11-26 18:37:11
Original
192 people have browsed it

Why Does `bottom: 0` in Sticky Positioning Act Opposite to Expectations?

Unexpected Behavior with Sticky Positioning: bottom: 0

In exploring the CSS position property, developers may encounter an unexpected behavior when specifying bottom: 0 for sticky positioning. According to the MDN documentation, sticky elements are initially treated as relative position elements until a specified threshold is met, at which point they switch to fixed positioning. However, when bottom: 0 is specified, the opposite behavior occurs.

Expected Behavior vs. Actual Behavior

The MDN documentation suggests that elements with bottom: 0 should be relative when below the viewport and fixed when above it. However, the actual behavior is reversed: elements are fixed when below the viewport and relative when above it.

Explanation

This discrepancy stems from the wording of the MDN documentation. It states that sticky elements are treated as relative until the threshold is exceeded, not necessarily starting as relative. In the case of bottom: 0, the threshold is effectively exceeded from the start, as the element begins below the bottom of the viewport. Therefore, the element starts as fixed and becomes relative when scrolled beyond its starting point.

Example Illustration

Consider the following HTML and CSS code:

<body>
Copy after login
.a {
  margin-top: auto;
  position: sticky;
  bottom: 0;
}

.b {
  position: sticky;
  top: 0;
}
Copy after login

In this example, element A starts as relative and becomes fixed when scrolled down. Element B, on the other hand, starts as fixed and becomes relative when scrolled up. This behavior aligns with the actual behavior described above, where bottom: 0 results in fixed positioning at the outset.

The above is the detailed content of Why Does `bottom: 0` in Sticky Positioning Act Opposite to Expectations?. 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