How can I evenly balance text over multiple lines?

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]


If I understand what you're asking (and if I do, the general theme of 'use justify' doesn't quite do it), I don't think you'll be able to avoid writing a fair bit of JavaScript.

The only way I can see to do what you're asking would be to compare the width of the text to the width of the container, and adjust accordingly.

Formula: Width of a single line = width of text / roundUp(width of text/width of container)

i.e. (probably needs some adjustment to prevent it cutting words in half)

var widthOfText = functionToGetWidthOfText(width); //==120
var widthOfContainer = container.width(); //==100
var containerWidth = widthOfText / ceil(widthOfText/widthOfContainer);
// containerWidth = 120 / ceil(120/100) == 120 / 2 == 60
var formattingTextContainer.width = containerWidth
// text would go inside the formattingTextContainer, which would
// give you 2 lines of equal, 60px width

However, the issue with this is, making a "functionToGetWidthOfText". After some quick searching, all I have found is this stack overflow question where the answer is to...

Wrap text in a span and use jquery width()

i.e. put it in an element and measure how wide it is...you might be able to do that off-screen somewhere/delete it after fast enough no-one sees it, but that will probably take quite a few lines of JavaScript! (I might investigate this more after work...)

The reason you can't flat-out figure out the width without rendering it is due to the various font types and sizes that it could be represented with. So if you are always using an exact font-type and font-size, you might be able to write a function that does it without rendering it.