Make lines of text have equal length

前端 未结 4 1058
刺人心
刺人心 2021-02-07 15:44

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          


        
4条回答
  •  花落未央
    2021-02-07 16:24

    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.

提交回复
热议问题