Preventing relayout due to scrollbar

2019-01-18 12:43发布

问题:

How can I prevent the body of the page being "pushed" to the left when a scrollbar appears due to ajax content? I can of course set overflow:scroll to the body, but it wouldn't look nice.

I am using bootstrap, but I guess it is a general question.

回答1:

You can create a container that have a fixed width, and give the content the same width (same static width - not 100%). that way, when the content overflows the parent, the scroll will not push the content but will flow above it.

using that, you can apply a cool way to scroll without pushing anything. by showing the scroll only when you hover the container.

Check out this simple Demo

EDIT: Here I show the difference between setting static width, and %.



回答2:

Well, the scrollbar will always push your content aside, there is really nothing you can do about that. What you can do is to always show to scrollbar for example:

html,body {
    height:101%;
}

or

html {
    overflow-y: scroll;
}


回答3:

overflow: overlay

Building on avrahamcool's answer, you can use the property overflow: overlay.

Behaves the same as auto, but with the scrollbars drawn on top of content instead of taking up space. Only supported in WebKit-based (e.g., Safari) and Blink-based (e.g., Chrome or Opera) browsers.

Source: MDN

This is great for when you need horizontally-scrolling content and don't want it to change size when scrollbars appear on hover. However, it's marked on MDN as deprecated, so future support is uncertain.

Demo: jsfiddle.net/NKJRZ/385/