Automatically decrease font size for long words

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.

Leave a Comment