1

Goal: create scrolling content overlaid by an equally wide navbar. Example html could look like:

<div class="scrollable">
  <div class="content"></div>
</div>
<div class="navbar"></div>

Criteria:

  • .content fills a percent width of .scrollable, and is horizontally centered
  • .scrollable should have scrollbars
  • .navbar is exactly as wide as .content, centered exactly atop .content
  • Scrollbar width should be treated as unknown
  • Avoid javascript running via scroll, requestAnimationFrame, setInterval, etc. Ideally no js.

The most intuitive approach fails since the scrollbar causes a discrepancy in dimensions:

.container {
  position: absolute;
  width: 80%; height: 80%; left: 10%; top: 10%;
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.3);
}
.scrollable {
  position: absolute;
  width: 100%; height: 100%; left: 0; top: 0;
  overflow: hidden visible;
}
.scrollable > .content {
  width: 80%; margin: 60px auto;
  background-color: rgba(0, 0, 0, 0.2); text-align: center;
}
.navbar {
  position: absolute;
  left: 10%; bottom: 0; width: 80%; height: 50px;
  background-color: rgba(255, 0, 0, 0.3); color: rgba(255, 255, 255, 1);
}
<div class="container">
  <div class="scrollable">
    <div class="content">abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/>abcd<br/><br/><br/></div>
  </div>
  <div class="navbar">I am navbar</div>
</div>

The issue here is that .content takes up a percentage width of .scrollable's width minus its scrollbar width, whereas .navbar is set to a percentage width of .scrollable including its scrollbar width.

What is the best way to get around this discrepancy?

Gershom Maes
  • 7,358
  • 2
  • 35
  • 55

1 Answers1

0

check the answer in the codepen : https://codepen.io/the-wrong-guy/pen/vYLzRZZ

And you should use position: fixed instead of position: absolute to fix the navbar at the top

KALITA
  • 716
  • 2
  • 8
  • 20
  • This looks very close to what I'm interested in - but in your codepen the `.scrollable` element is actually not scrollable (even though I didn't list this as a criteria I was hoping it was implied by the class name). Your example looks like it works, but only because the `html` element, not `.scrollable`, is scrolling. (It works even if I add `.scrollable { overflow: hidden; }`) – Gershom Maes Jul 15 '20 at 21:26
  • yeah i forgot to remove the `overflow-x`, but it will scrollable if only the content overflows i think that's what you want – KALITA Jul 16 '20 at 05:12
  • Would you mind trying to update your code? (And maybe include it as a snippet in your answer! More accessible that way.) – Gershom Maes Jul 16 '20 at 13:06