Summary
There are three different methods to address this issue, each with its own unique characteristics:
Explore the StackBlitz demo for a visual demonstration
To witness the content shift in action, press "Toggle height".
Scrollbar Gutter
Although it has limited support, combining this technique with @support
media query alongside overflow-y: scroll
ensures a stable layout:
html {
overflow-y: scroll;
}
@supports (scrollbar-gutter: stable) {
html {
overflow-y: auto;
scrollbar-gutter: stable;
}
}
By implementing this method, content will always remain intact without any shifting.
The drawback here is that there will always be a fixed space reserved for the scrollbar.
Overflow: Overlay
With limited support, this approach hides anything it overlays and necessitates caution to avoid hiding essential content, especially during zoom or text size alterations.
It can be used in conjunction with scrollbar-gutter
:
html {
overflow-y: scroll;
}
@supports (scrollbar-gutter: stable) {
html {
overflow-y: auto;
scrollbar-gutter: stable;
}
}
@supports (overflow-y: overlay) {
html {
overflow-y: overlay;
scrollbar-gutter: auto;
}
}
An alternative involves negative margin and overflow-x: hidden
, but this poses a risk of concealing vital content under specific circumstances like small screens or customized font sizes.
Calc(100vw - 100%)
This method supports RTL directionality:
html[dir='ltr'] main {
padding-left: calc(100vw - 100%);
}
html[dir='rtl'] main {
padding-right: calc(100vw - 100%);
}
In this scenario, where <main>
serves as the container for centered content, content remains unaffected as long as the container dimensions do not exceed <main>
. However, once it reaches 100% width, padding will be introduced. Refer to the StackBlitz demo and select "Toggle width" for clarification.
.
The challenge here lies in the necessity of media queries to prevent padding on smaller screens, which may result in slight content shifts due to insufficient space for both 100% content and a scrollbar even on small screens.
Conclusion
Consider utilizing scrollbar-gutter combined with overlay techniques. For those averse to empty spaces, experimenting with the calc
solution accompanied by media queries could provide a viable option.