overflow-anchor
Definition
The overflow-anchor property is used to control the scrolling behavior when a user clicks on a link that refers to an element on the same page (i.e. a fragment identifier or a named anchor). When this property is set to auto, the user's viewport will be scrolled so that the target element is at the top of the viewport. When set to none, the user's viewport will not be scrolled.
Examples
This example sets the overflow-anchor property to auto for the entire page, meaning that clicking on a link that refers to an element on the same page will cause the user's viewport to scroll so that the target element is at the top of the viewport:
html {
overflow-anchor: auto;
}
This example sets the overflow-anchor property to none for all h2 elements on the page, meaning that clicking on a link that refers to an h2 element will not cause the user's viewport to scroll:
h2 {
overflow-anchor: none;
}
This example sets the overflow-anchor property to auto for all links with the class scroll-link, and adds some padding to the links to ensure that the target element is not obscured by a fixed header or navigation bar:
a.scroll-link {
overflow-anchor: auto;
padding: 10px;
display: block;
}
Values
Value | Description |
---|---|
auto | When a user clicks on a link that refers to an element on the same page, the user's viewport will be scrolled so that the target element is at the top of the viewport. This is the default value. |
none | Clicking on a link that refers to an element on the same page will not cause the user's viewport to scroll. |
Best Practices
- Use overflow-anchor: auto; for most elements on your page, to ensure that clicking on a link that refers to an element on the same page scrolls the user's viewport to the target element.
- If you have fixed headers or navigation bars that might obscure the target element, consider adding some padding to the element or using JavaScript to adjust the scroll position to ensure that the target element is fully visible.
- If you have multiple links on the page that refer to the same element, ensure that they all have the same id attribute to avoid confusion and unexpected behavior.
- Be mindful of the performance implications of using overflow-anchor: auto; on large pages with many links, as it can cause a lot of scrolling and repaints. Consider using JavaScript to handle the scrolling behavior instead.
- Test your website on different browsers to ensure that the overflow-anchor property is being applied correctly and that clicking on links that refer to elements on the same page works as expected.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | No | No | No | No |