A colleague required a quick solution by which the first word of each heading in her design would be of a different color than the rest of the words in that heading. Using a <span> element for a part of the heading (say, <h1>) and styling it with CSS to apply a different color should have sufficed. The challenge was, however, to make it work as a generic rule for all <h1> elements since the website she was working on was CMS-based and more headings could be added later in different pages and putting a <span> around the first word of each heading individually was out of the question.

This is the solution I provided wherein the first word of each <h1> element in the page is picked using jQuery and gets wrapped by a <span> with a class called “h1firstword”  :


        $('h1').each(function() {
            var h = $(this).html();
            var index = h.indexOf(' ');
            if(index == -1) {
                index = h.length;
            $(this).html('<span class="h1firstword">' + h.substring(0, index) + '</span>' + h.substring(index, h.length));


Note: It goes without saying that you need to include the jQuery library in your page before you expect the above script to work.

Now simply style h1 and .h1firstword using CSS any which way you want.

Here is what I applied to test :


font-family: Arial, Helvetica, sans-serif;




font-family:Georgia, "Times New Roman", Times, serif;



Now you can write as many <h1> headings on the page you want, and each of them will have their first words styled differently from the rest of the words… automagically! ;-)

In my next post I will discuss how to style the first letter (or character or whatever it is you type in) differently than the rest of the heading. So stay tuned!

Latest posts by Smarajit Dasgupta

  • Share/Bookmark