Search code examples
javascripthtmlcssword-wrap

How can I evenly balance text over multiple lines?


I'd like to display a short piece of text that may wrap to two or three lines. It's inside a highly visual element and for styling purposes I'd like the lines to be as equal in length as possible, preferring one line over two.

Instead of this:

This is an example of a piece of text that will wrap to two

lines.

I want this:

This is an example of a piece of

text that will wrap to two lines.

But I don't want to limit the width of the text container:

This text is long enough to just barely fit in two lines. It

should not wrap to three or more lines so no width limiting.

Is there a way to do this in pure CSS or with a tolerable amount of JavaScript?


Solution

  • The CSS Text Module 4 property:

    text-wrap: balance;
    

    will do this. https://drafts.csswg.org/css-text-4/#text-wrap

    There's also a package which implements a polyfill for existing browsers.

    Here's a demo of balance text. [Archived copy]