Flexbox: How to prevent <pre> elements from overflowing

Updated . Posted . Visible to the public.

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

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:

Florian Leinsinger
Last edit
Florian Leinsinger
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Florian Leinsinger to makandra dev (2022-04-05 14:23)