This tutorial shows how to style and change the first letter of a paragrapher in a WordPress post using CSS and JQuery
This tutorial aims to style and change the first letter of an HTML paragraph of the first paragraph (and only the first) of a WordPress post content or page content.
Styling the first letter of a CSS div is very straightforward, CSS provides a selector called “::first-letter” that gets the job done, it finds the first letter of a specified div and changes its style. Please have a look at the documentation from mozilla.org in this link for more information.
In this case, I will provide the CSS of the first letter style that this website uses, but please keep in mind that you can use any type of border, background, colour etc.. that will be applied to the first letter. For the purpose of this tutorial I will create a CSS class called “first-letter” that I will add to the first paragraph that I will find through JQuery.
Here is the CSS:
.first-letter:first-letter{ color: #2e266f; margin: -0.25rem .3rem 0 .3rem; font-size: 3rem; float: left; line-height: 1; text-shadow: -1px 2px 0 #fff, -4px 4px 0 #646464; }
As I said you are free to apply any type of style to this CSS above and play around with the code since you will find the result that fits your website the best. Here are a few example of CSS code that you could add inside the code above:
/* create a background */background-color: red;
/* create a border */padding: 0 .3rem;
margin: 0 .3rem 0 0;
border: 2px solid;
border-radius: 8px;
However, finding the first paragraph of a page or post in WordPress can be a bit more tricky than we think though, any WordPress theme has a different design, different template page and the CSS classes obviously don’t match, we are not even sure that the first DIV of the post is a paragraph, it could be an H2 or an image.
So to make this feature standard and work on any page of our website I suggest creating a JQuery script that searches for the first <p> child of the content CSS class of a page and injects the CSS classes that we just created “first-letter”. In my case, the content CSS class is called ‘entry-content’, so here is the JS code:
jQuery(function ($) { // find first child <p> of class '.entry-content' var first_page_p = $('.entry-content').find("p:first"); // check if element exists if (first_page_p.length > 0) { // add the CSS class 'first-letter' first_page_p.addClass('first-letter'); } });
Please leave a comment if you found this tutorial useful. 🙂