Search code examples
htmlcsswhitespaceword-wrappre

Wrapping <pre> to a fixed width such that each line is the same length in characters


I'm attempting to wrap this long <pre> so that it forms a rectangle (rather than having the "jagged" endings I'm getting). I've set white-space to pre-wrap and word-break to break-all like other StackOverflow posts have suggested, but it seems like the browser is still applying some heuristics on where to break the line.

I cannot break the <pre> into rows a-priori because both the length of the content, as well as the width of the <pre> may be dynamic.

pre {
  width: 300px;
  white-space: pre-wrap;
  word-break: break-all;
}
<pre>ER..............................3......|..f1.f1.fSfQ.W....R..|.........K...R.A..U1.0....r...U.u....t.f.....B....1.ZQ....[...@P..?Q..SRP..|[email protected].&gt;@|..xpu....{.D|.....isolinux.bin missing or corrupt...f`f1.f...{f...{fRfP.Sj.j...f.6.{.........6.{....A......{...d.fa....Operating system load error...^....&gt;b.....&lt;.u........................</pre>

What I have:

preformatted text with unequal line lengths

What I want to achieve:

preformatted text with equal line lengths


Solution

  • line-break: anywhere; works well in Chrome (Canary) and Firefox, but not Edge. If the content contains spaces, you should probably use white-space:break-spaces rather than pre-wrap as well.

    pre {
      width: 300px;
      white-space: break-spaces;
      line-break: anywhere;
    }
    <pre>ER..............................3......|..f1.f1.fSfQ.W....R..|.........K...R.A..U1.0....r...U.u....t.f.....B....1.ZQ....[...@P..?Q..SRP..|[email protected].&gt;@|..xpu....{.D|.....isolinux.bin missing or corrupt...f`f1.f...{f...{fRfP.Sj.j...f.6.{.........6.{....A......{...d.fa....Operating system load error...^....&gt;b.....&lt;.u........................</pre>