Styling the First Word
CSS doesn’t have a pseudo class for first-word (only first-line and first-letter) but here is a simple tip for WordPress users: You can add a few lines of code to your WordPress theme which allow you to style the first word of any page title differently than the rest of the title. Here’s an example of what it might look like:
The code:
<?php
$space_pos = strpos(get_the_title(),' ');
$before = '<span class="first-word">';
$after = '</span>';
if($space_pos)
{
$title = $before.get_the_title();
$title = substr_replace($title,$after.' ',$space_pos+strlen($before),1);
}
else $title = $before.get_the_title().$after;
?>
How it works
The first line checks if there is more than one word in the title. If there is, the if statement adds a span with the class “first-word” around the first word. If there is only one word in the title, the else statement adds the span around the entire title. If you want to use something other than a span or give the class a different name, just change the variables for before and after.
How to add it to your theme
- Add the above code at the top of your template file.
- Replace “<?php the_title(); ?>” with <?php echo $title; ?> in the same document.
- Add whatever styling you wish to your CSS file.
Not sure where your theme files are? Look in your WordPress theme folder: wp-content/themes/ then the name of your active theme. Look for a file called page.php for Pages and a file called single.php for Posts. You can add the CSS to the styles.css file in the same directory. For example…
CSS Example
.first-word {
font-style:italic;
font-size:2em;
}
Tags: Wordpress
December 5th, 2011 at 9:07 pm
Thanks for the help… great piece of code here!
August 12th, 2012 at 6:42 am
Thanks !!