Is there a way to prevent scrollbar from pushing content, or the entire page to the left with pure css? I mean no hacks or anything.
I tried two javascript solutions:
1) Set body to overflow hidden, store the body.offsetWidth in a variable, then overflow visible and then subtract that offsetWidth with the current body.offsetWidth and apply the difference to the right margin.
2) Calculate the offsetWidth and apply it on the wrapper div on every resize.
What didnt work:
1) Position absolute.
2) Floating everything to the left was a bad idea.
3) Leaving the scrollbar visible (Looks bad).
4) Overflow-y hidden makes things user unfriendly.
The easy fix is to use width: 100% instead. Percentages don't include the width of the scrollbar, so will automatically fit. If you can't do that, or you're setting the width on another element, add overflow-x: hidden or overflow: hidden to the surrounding element to prevent the scrollbar.
There's another way to disable scrolling that is commonly used when opening modals or scrollable floating elements. And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.
To hide the scrollbar and disable scrolling, we can use the CSS overflow property. This property determines what to do with content that extends beyond the boundaries of its container. To prevent scrolling with this property, just apply the rule overflow: hidden to the body (for the entire page) or a container element.
There are a lot of ways to go around this issue though normally you won't mind a little push to the left:
Give overflow-y: scroll
to body
and make sure always there is a scrollbar.
Make use of the fact that viewport width includes the scrollbar while percentages do not account for it:
a. Giving width: 100vw
to body
element, or
b. Giving margin-left: calc(100vw - 100%)
to the html
element so that scrollbar or not, you have a fixed area to work on.
There is even a deprecated overflow: overlay
property that draws over the page instead of shifting it to the left.
Just give your body a width of 100vw like this:
body{
width: 100vw;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With