Adding Class Names to Dynamic Text Based on Length of Characters in Longest Word

Adding Class Names to Dynamic Text Based on Length of Characters in Longest Word

Posted by Rainey

In finalizing our most recent WordPress theme, I found that the design had pushed me into a corner.

The Problem: The WordPress theme under development places the site title in a confined area. In this situation the title lives in an area about 200 pixels wide. The title does wrap but if the site administrator needs to enter some long title with no spaces, then the sky starts falling.

Getting over this hurdle can be done with a short bit of PHP.

				$string = get_bloginfo('name'); //store site name as a string
				$words  = explode(' ', $string);
				$className = '';
				$longestWordLength = 0;

				foreach ($words as $word) {
				   if (strlen($word) > $longestWordLength) {
				      $longestWordLength = strlen($word);
				//after we know how long the word is, we can style it accordingly
				if ($longestWordLength < 10) {$className = "logoTextLarge";}
				else if ($longestWordLength >= 10 && $longestWordLength < 15) {$className = "logoTextMedium";}
				else if ($longestWordLength >= 15 && $longestWordLength < 20) {$className = "logoTextSmall";}
				else {$className = "logoTextXSmall";}
			<h1><a href="<?php bloginfo('url'); ?>" class="<?php echo $className; ?>"><?php bloginfo('name'); ?></a></h1>

So, if the longest word in the title is 14 characters long, the code above will render <h1><a href=”” class=”logoTextMedium”….

A quick walk through, first the name of the site is stored as a string.  Next, we use the explode function to break the string title into an array.  Now we can step through the array of words to determine which is the longest one.  Finally, based on the number of characters in the longest word, apply an appropriate class to the text output so it can be controlled with CSS.

/*Styles applied based on the length determined above */
.logoTextXSmall {
	font-size: 11px;
	line-height: 14px;

	font-size: 14px;
	line-height: 15px;

.logoTextMedium {
	font-size: 17px;
	line-height: 21px;

.logoTextLarge {
	font-size: 22px;
	line-height: 26px;

Checkout a post on Stackoverflow, longest word in a string, to see the basis for this solution.

Like what you are reading? Subscribe to receive monthly tips & updates!

A Monthly Roundup of Articles and a Sweet Deal

Get the latest tips, tricks, tutorials and freebies in your inbox once a monthly.

Join our growing community of front-end web developers and designers. We are constantly publishing new industry tips, tricks and tutorials to help you take your game to the next level. We are also going to include a freebie or deal on something cool each month. Enter your email below and you will only receive this email once a month, nothing else.

Subscribe to our mailing list

* indicates required

    Today in Web Design - Tutorials
    Tagged | , , , ,