How to style the first word of a sentence
A cool trick is to sometimes style the first word in a sentence. This is particularly useful with headlines by underlining the first word.
Insert a headline block, make it an H2
and assign it a class of underline-first-word
from the options on the right.
Now the fun part. We are going to write some JavaScript code that will split any sentence we want into <span></span>
elements to assist us with styling. No need to mess with the headline HTML code, either, the code will do the work for us! Create a GeneratePress hook element and set it to be displayed at the footer. On the element Display Rules, select where you want that element to appear. You can select “Entire Site”, but if you only want to style a headline on a certain page, select only that page so that the code doesn’t load on all the pages of your site. Enter the following code into the hook text area:
<script> var h1s = document.getElementsByTagName('h2'); for(var i=0; i < h1s.length; i++) { var t = h1s[i]; t.innerHTML = '<span>' + t.innerHTML . split(' ') . join('</span> <span>') + '</span>'; } </script>
Your element should like something like this.
Make sure that there is a space between the two <span> elements in this part of the code:
join('</span> <span>')
Now, write some simple CSS to target the first word of your headline:
h2.underline-first-word span:first-child { text-decoration: underline; }
And voila! Your H2
headline should look something like this:
Of course, you can apply any kind of styling of your choosing to your headline as long as the underline-first-word
class is present!