The CSS scroll-margin-top
property can be used to prevent a focused element from being hidden behind a fixed header or other fixed element when it is scrolled into view.
When an element is focused, it will be scrolled into view if it is not already visible in the viewport. However, if there is a fixed element, such as a header, that is positioned above the focused element, the focused element may be hidden behind the fixed element. This can be particularly problematic on mobile devices with smaller screens.
To prevent this issue, you can use the scroll-margin-top
property to add a margin to the top of the element that is being focused, equal to the height of the fixed header. This will ensure that the focused element is scrolled into view below the fixed header.
Example:
button {
scroll-margin-top: 50px; /* Set scroll margin equal to the height of the fixed header */
}
Overflow Property Affecting Scroll-Margin-Top
When using the CSS scroll-margin-top
property to prevent a focused element from being hidden behind a fixed header, it’s important to keep in mind that the scroll-margin-top
property can be affected by the overflow
property of the parent element.
Specifically, if the parent element has overflow: hidden
set, it can prevent the scroll-margin-top
property from working correctly. This is because overflow: hidden
clips any content that overflows the element, which can include the margin added by scroll-margin-top
.
In other words, if the parent element has overflow: hidden
set and the scroll-margin-top
property is used on a child element, the margin added by scroll-margin-top
may be clipped by the parent element, which can result in the focused element still being hidden behind the fixed header.
To avoid this issue, you can try using overflow: clip
instead of overflow: hidden
. This will ensure that the margin added by scroll-margin-top
is not clipped, and the focused element will be scrolled into view below the fixed header as expected.