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
position:sticky
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>
<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>
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!