CSS for changing color of last word in h1

Solution 1:

This is not possible with pure CSS. However you can use lettering.js to get a ::last-word selector. CSS-Tricks has an excelent article on this: CSS-Tricks: A call for nth-everything. You can then do the following:

h1 {
  color: #f00;
}

/* EDIT: Needs lettering.js. Please read the complete post,
 * before downvoting. Instead vote up. Thank you :)
 */
h1::last-word {
  color: #00f;
}

Solution 2:

"last-word" won't work on every browser; for instance, it doesn't work with Safari. I wouldn't use the accepted answer. I don't think it's a good idea to import an entire library or plugin just to change the last word of a single title, it's like "killing a bug with a cannon"... Instead I would use a single Javascript function, and a global class. Something like this:

<h1>This is my awesome <span class="last-word">title</span></h1>

CSS:

<style>
    .last-word {font-weight:bold; /* Or whatever you want to do with this element */ }
</style>

Initially, you would have something like this:

<h1 class="title">This is my awesome title</h1>

Then, you could initialize a Javascript method to change the last word on $(document).ready() =>

<script>
    $(document).ready(function() {
        $('.title').each(function(index, element) {
            var heading = $(element);
            var word_array, last_word, first_part;

            word_array = heading.html().split(/\s+/); // split on spaces
            last_word = word_array.pop();             // pop the last word
            first_part = word_array.join(' ');        // rejoin the first words together

            heading.html([first_part, ' <span class="last-word">', last_word, '</span>'].join(''));
        });
    });
</script>

Good luck.

Solution 3:

No, there is not. Only ::first-letter and ::first-line exist in CSS. Anything else must be done manually with an element (e.g. span).

Note: Neither ::first-word nor ::last-word are planned, at least not in the Selectors level 4 spec.