htmlcssfirefoxwhitespacenowrap

white-space: nowrap resizes parent but does not respect scrollbar


I have a sidebar with some text that must not wrap. If the text is too big for the container, I want the container (i.e. the sidebar) to expand. Here is an MVP of the problem:

<html>
<body>
  <div class="sidebar">
    <span>This is some text that must not wrap.</span>
    <div class="etc"></div>
  </div>
</body>
</html>
* {
  box-sizing: border-box; 
  margin: 0;
}

body {
  height: 100vh;
  display: grid;
  grid-template-columns: auto 1fr;
}

.etc {
/* Just for demo purposes to ensure a scrollbar appears.   */
  height: 200vh;
}

.sidebar {
  overflow-y: auto;
}

.sidebar span {
  white-space: nowrap;
  overflow: auto;
}

This results in the following:

screenshot showing the scrollbar overlapping the text content

Adding more text does increase the container width, but it's always short by the width of the scrollbar.

Why does this happen, and how can I fix it? Preferably not by adding a scrollbar width's worth of padding/margin to the right.

For transparency, the actual codebase has more complex markup (see below). In this case, whichever of the p:last-child elements is longest will go underneath the scrollbar (or both if they're of similar length).

<body>
<ul>
    <li>
        <a>
            <div>
                <h2>Title</h2>
                <p>This is underneath the scrollbar.</p>
            </div>
            <div>
                <p>Some text...</p>
                <p>This is also underneath the scrollbar if it's long enough.</p>
            </div>
        </a>
    </li>
    ...
</ul>
</body>

Solution

  • Thanks @zer00ne and @Alohci for your comments, both overflow-y: scroll and scrollbar-gutter: stable work for my use case.

    Obligatory caniuse for the latter.