Table of Contents

About

Sticky is a positioning option 1) 2) that:

From a logical point of view, the element is treated:

Implementation

The pinning (sticking) of an element is enabled through:

Css

In Css, Sticky positioning:

  • keeps the box in view
  • whenever possible
  • as the user scrolls.

In Css, Sticky positioning

  • calculate the position of the box first in the normal flow
  • move the box inside the sticky view rectangle defined via the offsets

Offsets are defined in reference to the nearest scrollport:

  • ie the view of a scrolling container
  • ie where you see the scroll bar (generally the page window)

Example: Just scroll the below example, the explanation comes later. This example shows:

  • a document of 300px height
  • inside a iframe of 150px height (leading to overflow, ie scrolling)
  • a page header of 100px height with a blue border
  • and a stick box of 100px height with a top offset of 50px and a red border
<div class="document" style="height:300px;">
   <div class="header" style="height:100px;border: 1px solid blue">
       Header
   </div>
   <div class="sticky-box" style="height:100px;top:50px;position:sticky;border: 1px solid red; overflow-y: auto">
      <p>Sticky box</p>
      <p>Sticky box</p>
      <p>Sticky box</p>
      <p>Sticky box Overflow</p>
      <p>Sticky box Overflow</p>
      <p>Sticky box Overflow</p>
   </div>
</div>

In the above example:

  • the sticky view rectangle of the sticky box is created relative to the nearest scrollable item (an iframe in our case of 150px)
    • with the top edge at 50px from the top of the iframe
  • it means that the sticky box got the following constraints:
    • it should always be located below 50px from the top of the iframe viewport (the nearest scrollable item)
    • the box content should not be clipped (the height of the box stays the same inside the container)
  • while scrolling, the sticky-box element:
    • cross the 50px top threshold and the sticky positioning scheme applies then the offset.
    • comes to the bottom of the document and shows the whole box on its whole height (does not clip the box)

Javascript

The Bootstrap Affix implements sticky positioning via class toggling that represents a particular state.

When the element scrolling past the offset limit provided by the “data-offset-” attribute the plugin replaces:

  • the .affix-top (top-most position) or .affix-bottom class (bottom-most position)
  • with the .affix class (sets position: fixed;), which trigger the actual affixing.