Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure css way to prevent scrollbar pushing content to the left?

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.

like image 393
Asperger Avatar asked Feb 19 '16 19:02

Asperger


People also ask

How do I stop the scroll bar from moving in CSS?

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.

How do you make the element not move when scrolling?

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.

How do you stop body scrolling in CSS?

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.


2 Answers

There are a lot of ways to go around this issue though normally you won't mind a little push to the left:

  1. Give overflow-y: scroll to body and make sure always there is a scrollbar.

  2. 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.

  3. There is even a deprecated overflow: overlay property that draws over the page instead of shifting it to the left.

like image 184
kukkuz Avatar answered Sep 26 '22 10:09

kukkuz


Just give your body a width of 100vw like this:

body{
   width: 100vw;
}
like image 25
Metatron5 Avatar answered Sep 25 '22 10:09

Metatron5