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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)