CSS scroll-margin-top attribute

Definition and Usage

scroll-margin-top property to specify the distance between the吸附位置 and the container.

吸附位置 refers to the fixed position of the child element in the container when the scrolling stops. The吸附位置 is specified by scroll-snap-align property settings, but may also be affected by CSS properties direction and writing-mode influence.

Note:This property is only effective when the吸附位置 is set at the top of the child element.

to see scroll-margin-top property effects on the parent element, and the吸附位置 must be set on the child element to see scroll-margin-top and scroll-snap-align property, and set scroll-snap-type Property.

Instance

Example 1

Set the top scroll margin between the吸附位置 and the container to 20px:

div {
  scroll-margin-top: 20px;
}

Try It Yourself

Example 2: Image Library

scroll-margin-top The property can be used in image galleries with吸附 behaviors. Here,scroll-margin-top Let the user know that there is another image at the top. Scroll past the first image to see the effect:

#container > img {
  scroll-margin-top: 30px;
}

Try It Yourself

Example 3:吸附位置

To make scroll-margin-top The property takes effect, and the吸附位置 must be set at the top of the child element. In this example,writing-mode The property changes the吸附位置 from the top of the child element to the right. Use the following code toscroll-margin-top The property will no longer take effect:

#container {
  writing-mode: vertical-rl;
}
#container > div {
  scroll-margin-top: 30px;
  scroll-snap-align: start none;
}

Try It Yourself

CSS Syntax

scroll-margin-top: 0;value|initial|inherit;

Property Value

Value Description
0 The top scroll margin is 0. This is the default value.
length

Specify the value of the top scroll margin in units such as px, pt, cm, etc. Negative values are allowed.

See:CSS Units.

initial Sets this property to its default value. See initial.
inherit Inherits this property from its parent element. See inherit.

Technical Details

Default Value: 0
Inheritance: No
Animation Creation: Not supported. See:Animation-related properties.
Version: CSS3
JavaScript Syntax: object.style.scrollMarginTop="20px"

Browser Support

The numbers in the table represent the browser version that first fully supports this property.

Chrome Edge Firefox Safari Opera
69.0 79.0 68.0 14.1 56.0

Related Pages

Reference:CSS direction attribute

Reference:CSS scroll-snap-align attribute

Reference:CSS scroll-snap-type attribute

Reference:CSS writing-mode attribute