Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically determine Font-Size for single-line display

I'm displaying articles on a page. The article titles sometimes spill over onto two lines, and may even have only a single word on the second line. This is very undesirable. Using jQuery/CSS, what would be the best method to programmatically determine a new font-size for the titles to keep them on one line?

like image 445
Sampson Avatar asked Jul 24 '09 12:07

Sampson


2 Answers

Kind of a hack but: Something like this will get you close. It likely needs a little more tweeking. Basically, it clones the element and sets the clone's text to &nbsp, so it gets an idea of what the height of one line would be. Then it decreases the element's font size until it's smaller than the target height.

Keep in mind you would also need to attach this function to the parent's resize().

$(document).ready(function() {
    $(".shrink").each(function() {
        var targetHeight = $(this).clone().html(" ").insertAfter($(this));

        while ($(this).height() > targetHeight.height()) {
            $(this).css("font-size", parseInt($(this).css("font-size")) - 1);
        }

        targetHeight.remove();
    });
});
like image 119
Nick Riggs Avatar answered Nov 14 '22 13:11

Nick Riggs


A simply solution would be to put an element right at the end of the line, and decrease the text size until its offsetHeight was correct. For example, wrap the full-stop in:

<span id="check">.</span>

You can now check where your full stop is, and reduce the text size until it's nearer to where you hoped. If you set the line-height on this particular phrase to be very large, it would make it easier to determine.

like image 1
Fenton Avatar answered Nov 14 '22 12:11

Fenton