Open In App

CSS scroll-margin Property

Improve
Improve
Like Article
Like
Save
Share
Report

The scroll-margin property is used to set all the scroll margins of an element at once. The value specified for the scroll-margin determines how much of the page that is primarily outside the support should remain visible.

Hence, the scroll-margin values represent outsets that define the scroll snap area that is used for snapping this box to the support. 

Syntax:

scroll-margin: length

/* Or */

scroll-margin: Global_Values

Property values: This property accepts two-properties mentioned above and described below:

  • length: This property refers to the values defined with length units exp: px, em, vh, etc.
  • Global_Values: This property refers to the global values like inherit, initial, unset, etc.

Note: scroll-margin doesn’t accept percentage value as the length. 

Example: In this example, you can see the effect of scroll-margin by scrolling to a point partway between two of the “interfaces” of the example’s content.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,
                  initial-scale=1.0">
     
    <style>
        .scroll {
            width: 350px;
            height: 350px;
            text-align: left;
            box-sizing: border-box;
            display: flex;
            overflow-x: scroll;
            scroll-snap-type: x mandatory;
        }
        .scroll > div {
            flex: 0 0 350px;
            width: 350px;
            font-size: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            scroll-snap-align: start;
        }
 
        /* Scroller will give 2rem margin
           from left */
        .scroll > div:nth-child(even) {
            background-color: rgb(77, 238, 184);
            color: #fff;
            scroll-margin: 2rem;
        }
 
        /* Scroller will give 5rem margin
           from left */
        .scroll > div:nth-child(odd) {
            background-color: #2dc06a;
            color: #fff;
            scroll-margin: 5rem;
        }
    </style>
</head>
 
<body>
    <div class="scroll">
        <div>Geeks</div>
        <div>for</div>
        <div>Geeks</div>
    </div>  
</body>
 
</html>


Output: When scrolling past the middle child elements, the scrolling will snap to 2rem outside the left edge of the even child div, and 3rem outside the left edge of the odd child div.

Supported Browsers:

  • Chrome 69
  • Firefox 90
  • Edge 79
  • Safari 14.1
  • Opera 56


Last Updated : 30 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads