Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Balancing a Header in HTML Using CSS/jQuery

Tags:

html

jquery

css

I have a lot of h2 headings in one of my websites. While most of those headings are "balanced" (this is a word I made up, since I have no better way to explain this), some are not balanced and look awful.

This is an example, which should make it clear:

enter image description here

(Arrow shows the orphan word).

As you can see in the image above, the first heading has an orphan word with a long first line, while the second heading is more proportionate.

Is there a way to achieve this effect without having to add <br> tags in my headings?

I know that I could just resize the heading container using a width attribute, but the problem doesn't go away since what I'm trying to avoid is those orphan words.

I'm not even sure if there's a solution to this, but it's something I've been wondering for some time.

like image 505
Joaquin De La Sierra Avatar asked Nov 09 '22 17:11

Joaquin De La Sierra


1 Answers

A possible approach would be to decrease a header's width until its number of lines increases. The width before the number of lines is increased is then the final width of the header. That should make it look "balanced".

Check this working fiddle that contains the code below.

// "Balance" a jQuery element
function balance($elem) {    
    var originalWidth = $elem.width(),
        originalHeight = $elem.height(),
        currentWidth = originalWidth,
        currentHeight = originalHeight;

    // Decrement width until number of lines increases or
    // width becomes 0
    while (currentHeight == originalHeight && currentWidth > 0) {
        $elem.width(currentWidth - 1);
        currentWidth = $elem.width();
        currentHeight = $elem.height();
    }

    if (currentWidth == 0) {
        // Reset width
        $elem.width('');
    } else {
        // Restore width so that number of lines is maintained
        $elem.width(currentWidth + 1);
    }
}
like image 50
nunocastromartins Avatar answered Nov 14 '22 22:11

nunocastromartins