4

I am working on an e-commerce site in which post and product titles will need to be displayed in fairly narrow divs. I would like to set a specific font size for words which can naturally fit in the space provided, while instructing words which are too long for the parent object's width to scale down automatically, thus avoiding the need for hyphenation. It seems someone must have thought of a way to do this before but I have been unable to find any solutions on the web. The closest I've found to an answer is the BigText jQuery plugin, but this is really designed for situations where you can predict your own line breaks. Since my titles will be queried by Wordpress and inserted altogether into divs, this plugin would shrink my texts until every word could fit on one line, which is not what I'm looking for. Please let me know if you have any suggestions. Thanks so much your time! Best, Jonathan

5

I’ve done something similar taking the simple approach of adding a CSS class to titles based on their character count. That CSS class then decreases letter-spacing and/or font-size.

// Count the characters, taking Unicode into account
$chars = mb_strlen($post->post_title);

// For every 10 characters after the first 20, add a size
$size = max(0, ceil(($chars - 20) / 10));

// Generate the CSS class: x-long, xx-long, etc.
$class = ($size) ? str_repeat('x', $size).'-long' : '';

// Output
echo '<h1 class="'.$class.'">'.esc_html($post->post_title).'</h1>';

This approach is quite naive, though. It doesn’t take into account the actual character width as rendered by the font. For that, you’d need a JavaScript approach.

  • Thanks a lot Geert! This is extremely helpful. I also discovered a plugin which uses jQuery to adjust the font size so the text always fills the entire element. Between these two solutions, I think my troubles are solved! Thanks so much! Here's the link to jQuery plugin: stackoverflow.com/questions/687998/… – jfudem Jun 17 '12 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.