How to prevent scrollbar from repositioning web page?
overflow-y:scroll is correct, but you should use it with the html tag, not body or else you get a double scrollbar in IE 7
So the correct css would be:
html {
overflow-y: scroll;
}
Material-ui: how to avoid dynamic content jumping because of scrollbar?
One possible workaround is to disable the scroll lock:
<SwipeableDrawer disableScrollLock={true} ... >
A downside of this is that you'll have to remember to do this everywhere you use any material-ui
component that has the disableScrolllock
functionality - so that means everywhere you use popovers, popups, etc.
But you can override the default props for components. The following worked for SwipableDrawer
(because Drawer
extends Modal
):
export const theme = createMuiTheme({
props: {
MuiModal: {
disableScrollLock: true,
},
},
});
Note: the disableScrollLock
setting appears to not be needed anymore with mui
(i.e. material-ui version 5
) - but you do still need to set style="overflow-y: scroll"
in your root body element or somewhere similar.
How to always show the vertical scrollbar in a browser?
jQuery shouldn't be required. You could try adding the CSS:
body {overflow-y:scroll;}
This works across the latest browsers, even IE6.
How Do I Stop My Web Content From Shifting Left When The Vertical Scrollbar Appears? Roll-Up of Advice 2017
Before going into individual solutions, it should be mentioned that they break down into three categories: CSS-, CSS3-, and Javascript-based solutions.
The CSS solutions tend to be rigid but very predictable and very well supported.
The CSS3 solutions have a CPU calculation cost like Javascript, but are easy to implement. In years previous to 2017, however, they had sporadic support in browsers. That is improving over time. Ultimately, they will likely be the best solution, but my own investigations today have demonstrated the support simply isn't consistent enough yet and, besides, legacy browser support is non-existent.
The Javascript solutions (whether in straight Javascript or in jQuery) need extra coding to make them robust as they have no intrinsic support for (e.g.) window resizing. However, they're the most predictable and the most backward compatible while still preserving the aesthetics of the page. I consider the line for legacy browsers to be between IE6 and IE7. Frankly, my condolences to anyone still using a browser that old.
Please note that I have not included every CSS3 and Javascript solution previously posted to Stack Exchange. Some, though novel, had substantial weaknesses and so were not included here.
**Solution #1: The CSS Solution**
Contributors: Hive7, koningdavid, Christofer Eliasson, Alec Gorge, Scott Bartell, Shawn Taylor, mVChr, fsn, Damb, Sparky, Ruben, Michael Krelin - hacker, Melvin Guerrero
Force the srollbar to always be on.
<style>
html {
overflow-y: scroll;
}
</style>
This solution is basically guaranteed to always work (there are some exceptions, but they're very rare), but it is aesthetically unpleasing. The scrollbar will always be seen, whether it's needed or not. While concensus is to use this solution in the html
tag, some people suggest using it in the body
tag.
Consequences
Microsoft (IE10+) has implented floating scroll bars which means your page may not be centered in it like it would be in other browsers. However, this seems to be a very minor issue.
When using structured interfaces like FancyBox, Flex-Box, or Twitter Bootstrap Modal this can cause a double-scrollbar to appear as those interfaces create their own scrollbars.
Programmers should avoid using overflow: scroll
as this will cause both the vertical and horizontal scrollbars to appear.
Solution #1a: An Alternative
Contributors: koningdavid, Nikunj Madhogaria
A clever alternative, but one having only a minor aesthetic difference, is to do this:
<style>
html {
height: 101%;
}
</style>
This activates the scroll bar background but doesn't activate the scroll bar tab unless your vertical content actually overflows the bottom edge of the window. Nevertheless, it has the same weakness in that the scrollbar space is permanently consumed whether needed or not.
Solution #1b: A More Modern Solution
Contributors: Kyle Dumovic, SimonDos
Browsers are beginning to pick up the use of the overlay
value for scrollbars, mimicking the floating scrollbar of IE10+.
<style>
html {
overflow-y: overlay;
}
</style>
This solution mimics the floating scrollbar in IE10+, but it is not yet available in all browsers and still has some implementation quirks. This solution is known not to work for infrastructure environments like Bootstrap Modal.
**Solution #2: The CSS3 Solution**
Use CSS3 to calculate widths. There are many ways to do this with advantages and disadvantages to each. Most disadvantages are due to (a) not knowing the actual scrollbar width, (b) dealing with screen resizing, and (c) the fact that CSS is slowly becoming yet-another-fully-functioning-programming language — like Javascript — but has not yet completely evolved into such. Whether or not it even makes sense for it to become such is a debate for another question.
The argument that users may disable Javascript and so a CSS-only solution is preferable is becoming irrelevant. Client-side programming has become so ubiquitous that only the most paranoid of people are still disabling Javascript. Personally, I no longer consider this a tenable argument.
It should be noted that some solutions modify margin
and others modify padding
. Those that modify margin
have a common problem: if you have navigation bars, headers, borders, etc. that use a different color than the page background this solution will expose undesirable borders. It is likely that any solution using margin
can be re-designed to use padding
and vice-versa.
Solution #2a: The HTML-based Solution
Contributors: TranslucentCloud, Mihail Malostanidis
<style>
html {
margin-left: calc(100vw - 100%);
margin-right: 0;
}
</script>
Solution #2b: The BODY-based Solution
Contributors: Greg St.Onge, Moesio, Jonathan SI
<style>
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
@media screen and (min-width: 1058px) {
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
}
</style>
100vw
is 100% of the viewport width.
Consequences
Some users have suggested this solution creates undesirable screen noise when the window is resized (perhaps the calculation process is occuring multiple times during the resize process). A possible workaround is to avoid using margin: 0 auto;
to center your content and instead use the following (the 1000px
and 500px
shown in the example represent your content maximum width and half that amount, respectively):
<style>
body {
margin-left: calc(50vw - 500px);
}
@media screen and (max-width: 1000px) {
body {
margin-left: 0;
}
}
</style>
This is a fixed-scrollbar-width solution, which isn't browser independent. To make it browser independent, you must include Javascript to determine the width of the scrollbars. An example that calculates the width but does not re-incorporate the value is:
Please note that the code snippet below has been posted multiple times on Stack Exchange and other locations on the Internet verbatim with no firm attribution.
function scrollbarWidth() {
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
// Append our div, do our calculation and then remove it
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}
Solution #2c: The DIV-based Solution
Contributors: Rapti
Use CSS3 calculations applied directly to a container DIV element.
<body>
<div style="padding-left: calc(100vw - 100%);">
My Content
</div>
</body>
Consequences
Like all CSS3 solutions, this is not supported by all browsers. Even those browsers that support viewport calculations do not (as of the date of this writing) support its use arbitrarily.
Solution #2d: Bootstrap Modal
Contributors: Mihail Malostanidis, kashesandr
Users of Twitter Bootstrap Modal have found it useful to apply the following CSS3 to their HTML element.
<style>
html {
width: 100%;
width: 100vw;
}
</style>
Another suggestion is to create a wrapper around your content wrapper that is used to auto-detect changes in the viewport width.
<style>
body {
overflow-x: hidden;
}
#wrap-wrap {
width: 100vw;
}
#content-wrap {
margin: 0 auto;
width: 800px;
}
</style>
I have not tried either of these as I do not use Bootstrap.
**Solution #3: The Javascript Solution**
Contributors: Sam, JBH
This is my favorite solution as it deals with all the issues and is reasonably backward compatible to legacy browsers. Best of all, it's scrollbar-width independent.
<script>
function updateWindow(){
document.body.style.paddingLeft = (window.innerWidth - document.body.clientWidth);
document.body.onclick=function(){
document.body.style.paddingLeft = (window.innerWidth - document.body.clientWidth);
}
}
window.onload=updateWindow();
window.addEventListener("resize", updateWindow());
updateWindow();
</script>
Consequences
The final command to updateWindow();
should occur just before the </body>
tag to avoid problems with dynamically-loaded content such as Facebook Like-Boxes. It would seem that it's redundant to the window.onload
event, but not every browser treats onload
the same way. Some wait for asynchronous events. Others don't.
The function is executed each and every time a user clicks within the web page. Gratefully, modern computers are fast enough that this isn't much of an issue. Still….
Finally, the function should be executed after any div is asynchronously updated (AJAX). That is not shown in this example, but would be part of the ready-state condition. For example:
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
if(xmlhttp.responseText == 'false'){
//Error processing here
} else {
//Success processing here
updateWindow();
}
}
}
Solution #3a: Measuring Scrollbar Widths
Contributors: Lwyrn
This is a less valuable solution that takes the time to measure scrollbar widths.
<script>
var checkScrollBars = function(){
var b = $('body');
var normalw = 0;
var scrollw = 0;
if(b.prop('scrollHeight')>b.height()){
normalw = window.innerWidth;
scrollw = normalw - b.width();
$('#container').css({marginRight:'-'+scrollw+'px'});
}
}
</script>
<style>
body {
overflow-x: hidden;
}
</style>
Consequences
Like other solutions, this one permanently disables the horizontal scrollbar.
Prevent a centered layout from shifting its position when scrollbar appears
I'm afraid the best way to solve this is to force the scroll bar to be visible at all times with html {overflow-y: scroll;}
. The problem you have is that the "available area" shrinks with say 10 px when the scroll bar appear. This cause the calculated margin on your left side to shrink with half the width of the scroll bar, thus shifting the centered content somewhat to the left.
A possible solution might be to calculate the margin with JavaScript instead of using margin: 0 auto;
and somehow compensate for the "lost" pixels when the scroll bar appear, but I'm afraid it will be messy and the content will probably move a little bit anyway while you calculate and apply the new margin.
Prevent scroll-bar from adding-up to the Width of page on Chrome
You can get the scrollbar size and then apply a margin to the container.
Something like this:
var checkScrollBars = function(){
var b = $('body');
var normalw = 0;
var scrollw = 0;
if(b.prop('scrollHeight')>b.height()){
normalw = window.innerWidth;
scrollw = normalw - b.width();
$('#container').css({marginRight:'-'+scrollw+'px'});
}
}
CSS for remove the h-scrollbar:
body{
overflow-x:hidden;
}
Try to take a look at this:
http://jsfiddle.net/NQAzt/
Prevent automatic browser scroll on refresh
This solution is no longer recommended due to changes in browser behavior. See other answers.
Basically, if an anchor is used we bind to the windows scroll event. The idea being that the first scroll event has to belong to the automatic repositioning done by the browser. When this occurs we do our own repositioning and then remove the bound event. This prevents subsequent page scrolls from borking the system.
$(document).ready(function() {
if (window.location.hash) {
//bind to scroll function
$(document).scroll( function() {
var hash = window.location.hash
var hashName = hash.substring(1, hash.length);
var element;
//if element has this id then scroll to it
if ($(hash).length != 0) {
element = $(hash);
}
//catch cases of links that use anchor name
else if ($('a[name="' + hashName + '"]').length != 0)
{
//just use the first one in case there are multiples
element = $('a[name="' + hashName + '"]:first');
}
//if we have a target then go to it
if (element != undefined) {
window.scrollTo(0, element.position().top);
}
//unbind the scroll event
$(document).unbind("scroll");
});
}
});
Related Topics
CSS Align Images and Text on Same Line
How to Play Shoutcast Internet Radio Streams with HTML5
How to Correctly Use "Section" Tag in HTML5
Dropdownlistfor Will Not Show The Correct Selection
Make a Parent Div Webkit-Filter Not Affect Children
Download Webpage and Dependencies, Including CSS Images
What Are All The Differences Between Src and Data-Src Attributes
Create Tree View with Horizontal and Vertical Lines Showing The Connectivity Using CSS
How to Prevent Text from Overflowing in CSS
Why Use Definition Lists (Dl,Dd,Dt) Tags for HTML Forms Instead of Tables
Stop Lastpass Filling Out a Form
How to Display Excel Sheet in HTML Page
How to Create a Curved Speech Bubble
How to Add HTML Code to Jsf Facesmessage