Cover Image for CSS sticky
126 views

CSS sticky

The CSS position: sticky; is a positioning property that allows an element to “stick” to a specified position within its containing element or the viewport as the user scrolls. It creates a sticky effect, where the element remains fixed in its position until it reaches a certain scroll threshold.

The position: sticky; property has three main states:

  1. Normal: The element behaves like a normally positioned element, following the normal flow of the document.
  2. Sticky: When the element reaches a specified scroll position, it becomes “stuck” in that position, and it no longer scrolls with the rest of the content. The sticky element will stay in place until it reaches another element that has its own position set to sticky, or until the user scrolls beyond a defined boundary.
  3. Relative: Once the user scrolls past the boundary (where the element becomes “stuck”), it will behave like a relatively positioned element, following the scrolling content.

The syntax for using position: sticky; is as follows:

selector {
  position: sticky;
  top: value; /* or bottom: value; */
}
  • selector: Represents the HTML element or class to which the position: sticky; property will be applied.
  • top or bottom: Specifies the position at which the element becomes “stuck” relative to its containing element or the viewport. You should set either top or bottom, but not both. The value can be expressed in pixels (px), percentages (%), or other length units.

Example:

.header {
  position: sticky;
  top: 0;
  background-color: #f1f1f1;
  padding: 10px;
}

In this example, the element with the class .header becomes sticky at the top of its containing element or the viewport (whichever is the closest) with a background color of #f1f1f1 and padding of 10px.

It’s important to note that position: sticky; is a relatively new feature in CSS and may not be fully supported in older browsers. For best results, ensure that your target browsers have good support for sticky positioning or provide alternative styles for older versions of browsers if necessary.

Using position: sticky; can be very helpful for creating sticky headers, navigation bars, sidebars, or any element that should remain visible while users scroll through the content.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS