3

When I click a thumbnail, it opens a div overlay box on top:

.view-overlay {
  display:none;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  overflow-y:scroll;
  background-color:rgba(0,0,0,0.7);
  z-index:999;
}

For browsers with non-floating scrollbars, disabling scroll with overflow: hidden removes the scrollbar causing the content to shift to the right a bit to make up for the additional space.

I want to keep the scrollbar there so that doesn't happen. There are solutions online but I can't find one that definitively works well in all browsers.

https://stackoverflow.com/a/13891717/4774917 - This answer seems to work well on Chrome, but causes weird glitchy behaviour on Safari OSX 10.10.

https://stackoverflow.com/a/8701977/4774917 - This answer causes the body to scroll back to the top (Chrome).

What's a solution that:

a) disables body scroll when the overlay is opened

b) keeps the body stay put at its original scroll position

c) keeps the scrollbar there so content doesn't shift

d) works on (most/all) browsers without glitchy behaviour?

Example: https://dribbble.com does this and it seems to work on the browsers I've tested it on (including Safari) without glitchy behaviour.

Community
  • 1
  • 1
frosty
  • 2,621
  • 3
  • 28
  • 52

1 Answers1

2

One approach that's both very simple and effective is to not have the main content in the body itself, but a wrapper that's a sibling with the overlay. With this approach you can toggle the overlay whenever necessary without affecting the scroll of the content element.

var e = document.getElementById('overlay');
document.body.onclick = function() {
  e.style.display = (!e.style.display || e.style.display === 'block') ? 'none' : 'block';
};
html,
body,
#content {
  height: 100%;
  margin: 0;
}
#content {
  overflow: auto;
}
#high {
  height: 800px;
}
#overlay {
  position: absolute;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
}
<div id="overlay"></div>
<div id="content">
  Long content resides in this container
  <div id="high"></div>
  And the long content ends here
</div>
Etheryte
  • 20,940
  • 10
  • 58
  • 98