Read more

Flexbox: How to prevent <pre> elements from overflowing

Florian Leinsinger
April 05, 2022Software engineer at makandra GmbH

I recently had the problem that embedded code boxes crashed my layout.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

It turned out that pres break out of their containers when using them inside a deeper nested flex layout.
For me it was a flex inside a flex item (fleXzibit).

Image

<div class="flex">
  <div class="flex-item">
    ...
    <div class="nested-flex">
      <div class="nested-flex-item">
        <pre>A code example</pre>
      </div>
    </div>
    ...
  </div>
</div>

The reason is that flexbox items default to min-width: auto, which leads to issues in calculating the available space for these pre elements. See: https://stackoverflow.com/a/28909778 Show archive.org snapshot

You can prevent this by adding the following to your CSS:

Note

min-width: stretch is an experimental feature Show archive.org snapshot

pre {
  min-width: -webkit-fill-available;
  min-width: -moz-available;
  min-width: stretch;
  max-width: 0;
}

You may know white-space: pre-wrap, but in most cases this is not what you want here. It simply prevents horizontal scrollbars and wraps the text inside the box at its maximum width without any indentation. This will make code blocks difficult to read.

See also:

Posted by Florian Leinsinger to makandra dev (2022-04-05 16:23)