Home > Web Front-end > CSS Tutorial > When Should I Use Position:Sticky vs Position:Fixed?

When Should I Use Position:Sticky vs Position:Fixed?

DDD
Release: 2024-11-04 10:16:30
Original
314 people have browsed it

When Should I Use Position:Sticky vs Position:Fixed?

Unveiling the Distinction Between position:sticky and position:fixed

Understanding the nuances between CSS positioning properties can be perplexing for beginners. This article delves into the subtle differences between position:sticky and position:fixed, clarifying their distinct functionalities to enhance your CSS prowess.

position:fixed vs. position:sticky

position:fixed

  • Locks an element to a specific position within its container or the viewport.
  • Stays fixed regardless of container scrolling.

position:sticky

  • Initially behaves like position:relative, which does not affect element flow.
  • Upon scrolling beyond a specified offset, transitions to position:fixed, "sticking" the element to its position.
  • Reverts to position:relative when scrolled back toward its initial position.

Example

Consider the following HTML and CSS:

<code class="html"><div class="container">
  <div class="sticky-element">Sticky Element</div>
  <div class="fixed-element">Fixed Element</div>
</div></code>
Copy after login
<code class="css">.container {
  height: 100vh; /* Set the container to full viewport height */
  overflow-y: scroll; /* Enable vertical scrolling within the container */
}

.sticky-element {
  position: sticky;
  top: 10px; /* Specifies the offset from the top before stickiness applies */
  width: 200px;
  height: 200px;
  background-color: blue;
}

.fixed-element {
  position: fixed;
  top: 0; /* Sets the fixed position from the top of the viewport */
  width: 200px;
  height: 200px;
  background-color: red;
}</code>
Copy after login

Behavior:

When scrolled, the sticky element remains in place until it reaches the top of the viewport, at which point it sticks to the top like a fixed element. The fixed element, on the other hand, remains glued to its initial position, regardless of container scrolling.

The above is the detailed content of When Should I Use Position:Sticky vs Position:Fixed?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template