Sobes.tech
Junior

What are the features of the position: sticky property?

sobes.tech AI

Answer from AI

position: sticky is a hybrid of position: relative and position: fixed.

  • Default behavior: The element behaves like position: relative, remaining in the normal document flow.
  • On scroll: When the element reaches a specified offset (e.g., top: 0) relative to its scroll container or viewport, it "sticks" and behaves like position: fixed, remaining visible at that position during further scrolling.
  • Offset: The offset is set using the top, right, bottom, left properties. At least one of these must be used for sticky to work correctly.
  • Scroll container (scroll container/containing block): The element "sticks" within its containing block, which usually is the nearest ancestor with scrolling capability or a specific formatting context. If only body/html scrolls, sticking is relative to the viewport.
  • Overlap: The sticky element can overlap content beneath it, similar to an element with position: fixed.
  • Z-index: The z-index property affects overlapping behavior.
  • Restrictions:
    • Does not work if the parent element has overflow: hidden, overflow: auto, or overflow: scroll, which clip content.
    • The element can "unstick" if it reaches the edge of its scroll container.
  • Usage: Commonly used for creating "sticky" headers for tables, navigation panels, or side elements that remain visible during main content scrolling.
/* Example usage */
.sticky-header {
  position: sticky;
  top: 0; /* Sticks to the top of the scroll container or viewport */
  background-color: white;
  padding: 10px;
  z-index: 10; /* Ensures the header appears above other content */
}