jQuery + CSS: Styling first character of a text differently
In my previous post I provided a jQuery and CSS-based solution for styling the first word of all headings in a page differently. Let’s look at a different scenario now where the first character of all headings (say, <h2> this time) in a page are different from the rest of the letters. The jQuery logic changes to:
var first = $(‘<span>’+text.charAt(0)+’</span>’).addClass(‘h2firstletter’);
$(this).html(text.substring(1)).prepend(first);
});
});
Here the first character in each h2 element gets wrapped by a span with a class “h2firstletter” applied. And then all you are left to do is style h2 and .h2firstletter using CSS.
I styled the following:
color:#0CF;
}
.h2firstletter{
font-family:Georgia, “Times New Roman”, Times, serif;
color:#F00;
On adding <h2> elements in the markup, the output on the browser would be like this:
Latest posts by Smarajit Dasgupta
- Playing with HTML5 - July 29th, 2011
- CSS Tutorial - June 7th, 2011
- 5 Tips for optimizing and cleaning up CSS - April 8th, 2011
- Introduction to HTML5 input types - April 1st, 2011
- Text level Semantics in HTML5 - March 17th, 2011

