Onjsdev

Share


Fixed vs Sticky In CSS


By onjsdev

Dec 29th, 2023

In CSS, fixed and sticky are two positioning properties that control the placement of an element within the document. In this article we will discuss the differences between them.

Fixed Positioning

When you set an element's position to "fixed," it is positioned relative to the viewport (the browser window) rather than its containing element

Here are key features of it:

  • Remains fixed to the viewport: The element stays in the same place on the screen even when the user scrolls.
  • Removed from normal document flow: It doesn't affect the layout of other elements.
  • Positioned relative to the viewport: You can position it using top, bottom, left, and right properties.
.fixed-element {
  position: fixed;
  top: 0;
  right: 0;
}

Common Use Cases Of Fixed Positioning

  • Navigation bars that always remain at the top or bottom of the screen
  • Overlays that cover the entire viewport
  • Tooltips anchored to specific elements

Sticky Positioning

A sticky element is a hybrid of relative and fixed positioning. It is treated as a relatively positioned element until it crosses a specified point (usually when the user scrolls past it), after which it is treated as fixed.

Here are key features of it:

  • Hybrid behavior: Acts as a regular element until it reaches a specified offset, then becomes fixed.
  • Limited to its containing block: It stays within its parent element and scrolls off the viewport with it.
  • Positioned relative to the containing block: You can use top, bottom, left, and right properties to set its position within its parent.
.sticky-element {
  position: sticky;
  top: 50px; /* When the element reaches this point, it becomes sticky */
}

Common Use Cases of Sticky Positioning

  • Table headers that stay visible when scrolling through long tables
  • Sidebar elements that remain in view as the user scrolls
  • Call-to-action buttons that stick to the bottom of the screen

Fixed vs Sticky

Here is the table that summarizes the comparison

FeatureFixedSticky
Relative toViewportContaining block
ScrollingStays in placeScrolls until offset, then sticks
ContainmentNot restricted by parentsLimited to parent element
Browser supportAll browsersMost modern browsers

Conclusion

In conclusion, we can say that:

  • Use fixed when you want an element to always remain in the same place on the screen, regardless of scrolling.
  • Use sticky when you want an element to scroll with the content until it reaches a certain point, then stay fixed within its parent element.

Thank you for reading.