Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make lines of text have equal length

In centered h1 elements, if the text falls on multiple lines, line breaks make the text look like this:

                This is a header that takes up two
                              lines

                This is a header that takes up three
                lines because it is really, really
                              long

Is there a way to manipulate these elements so that the length of the lines of text is roughly equal? Like this:

                       This is a header that
                        takes up two lines

                    This is a header that takes 
                     up three lines because it
                       is really, really long

The jQuery plugin Widow Fix prevents single-word lines, but I'm looking for something that evens out all the lines in a multi-line element. Are there any jQuery plugins for this, or can you recommend a strategy?

like image 995
supertrue Avatar asked Jan 30 '12 20:01

supertrue


2 Answers

Late to this party, but here's my approach. I get the initial element height (any elements with the class balance_lines, in the code below), then incrementally shrink the width of the element. Once the height of the element changes, I've gone too far. The step before that should have lovely roughly-equal line lengths.

$('.balance_lines').each(function(){
    var currentHeight = $(this).height();
    var thisHeight = currentHeight;
    var currentWidth = $(this).width();
    var newWidth = currentWidth;
    // Try shrinking width until height changes
    while (thisHeight == currentHeight) {
        var testWidth = newWidth - 10;
        $(this).width(testWidth);
        thisHeight = $(this).height();
        if (thisHeight == currentHeight) {
            newWidth = testWidth;
        } else {
            break;
        }
    }
    $(this).width(newWidth);
});

You can see this code in action on the homepage at apollopad.com.

like image 112
Dave Child Avatar answered Oct 14 '22 13:10

Dave Child


The CSS Text 4 draft proposes text-wrap: balance, but I don't think any browser implements it yet.

In the meantime, you can use Adobe's jQuery plugin (demo): https://github.com/adobe-webplatform/balance-text

like image 26
John Mellor Avatar answered Oct 14 '22 14:10

John Mellor