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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With