Skip to main content

Making an element sticky within a container

Front-end Development

Within certain user experiences, it’s helpful to keep important information visible to users at all times. A lot of the time, however, it’s better to keep information visible only while in the correct context (like scrolling through a particular section of a page). While we do have position: sticky available to us, this method does not allow us to pull the element out of the document flow prior to becoming fixed. In this article, we’ll be walking through the steps needed to achieve a sticky on scroll effect using CSS and jQuery.

Style the initial position

Start by setting the initial position of the element. I recommend using position: absolute because transitioning from absolute to fixed positioning is usually much simpler than transitioning from relative to fixed positioning.

.container {
  position: relative;
}

.element {
  position: absolute;
  top: 0;
  left: 0;
}

Because the plugin we'll be using applies position: fixed; top: 0; to the element, keeping the pixel values identical between states will ensure the smoothest transition. (Tip: Use padding or margins to add space around the element instead of top and bottom)

.element.fix {
  position: fixed;
  top: 0;
  left: 0;
}

Toggle between positions with jquery.stickOnScroll.js

Once all of the necessary “states” have been accounted for, the final step is to add the jQuery to toggle between each state on scroll. There are many jQuery plugins out there, but the one that I’ve had the most success with is jquery.stickOnScroll.js (opens in a new window). Download and add the plugin to your project, and then call the stickOnScroll() function in your custom jQuery:

$(".sticky-on-scroll").stickOnScroll();

The final result: