Shifting Box Alignment with scroll-margin in CSS

The scroLL-margin property, on the other hand, applies to the children of a scroll container. It adjusts the area of the box that gets aligned to the snapport. It doesn’t change the dimensions of the box to which it’s applied, but instead shifts its alignment position by the provided length. Let’s revisit our CSS from the scroLL-snap-aLign section:

.scroll-container p {

scroll-snap-align: none center;

}

Without scroLL-margin , each child of a Scroll Snap container will be centered within the snapport, as pictured below.

Let’s add a right scroLL-margin value of 200 pixels:

.scroll-container p {

scroll-snap-align: none center;

scroll-margin: 0 200px 0 0;

}

Now the center of our child element is shifted to the left by 200 pixels, due to this extra right margin, as shown below.

Values for scroLL-margin must be lengths. Negative values are perfectly valid, and scroLL- margin uses the same ordering as margin . Let’s change our right scroLL-margin value to a negative value.

.scroll-container p {

scroll-snap-align: none center;

scroll-margin: 0 -200px 0 0;

}

Now the center of our child element has been pulled 200 pixels to the right, as pictured below. This is, in effect, the same as using a positive scroLL-margin-Left value.

Much like scroLL-padding , the scroLL-margin property is a shorthand for the physical longhand properties. Values are ordered the same way as margin and scroLL-padding too: top, right, bottom, and left. You can also specify a margin value based on the inline or block direction:

  • scroLL-margin-top
  • scroLL-margin-right
  • scroLL-margin-bottom
  • scroLL-margin-Left

Logical longhand properties are:

  • scroLL-margin-inLine-start
  • scroLL-margin-bLock-start 
  • scroLL-margin-inLine-end
  • scroLL-margin-bLock-end

Here, too, scroLL-margin only affects the margin of a box along the axis of the overflowing content. If the scrolling direction is vertical, adding scroLL-margin-Left , scroLL-margin- right , or either of the scroLL-margin-inLine-* properties, won’t affect box alignment within the scrollport.

To date, there isn’t a way to change the Scroll Snap timing function using CSS. If you want that level of control, you’ll still need to use JavaScript.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *