As of 2022, you can achieve this without hard-coding widths by setting overflow: auto
on the element you want to scroll.
Often this isn't enough, because the element has already enlarged its parent before the overflow property is checked. So you usually have to set overflow: auto
on a bunch of parent/grandparent/etc. elements as well, to stop them from enlarging themselves. Normally this would mean they would also get scroll bars, but their children having overflow: auto
prevents this (because when the children scroll, there's nothing extending beyond the parents' boundaries).
It also helps to set one of the parents to display: flex
.
div.container {
display: flex;
flex-direction: column; /* Optional */
overflow: auto;
border: 1px solid red;
}
pre {
overflow: auto;
}
<html>
<body>
<div class="container">
<div>This text won't scroll</div>
<pre>
This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll. This is really long text that should scroll.
</pre>
</div>
</body>
</html>