For a project I am currently working on I wanted to use elevated initial capitals to set off each block of text. The obvious way to do this would have been with the :first-letter pseudo-element, which is what I initially did. This worked great in Safari, but in Internet Explorer, I got a series of bugs and idiosyncrasies that eventually became more trouble than they were worth. Line spacing was alternately too loose or too tight, depending on what I did, and in IE6 it interacted with the IE7-js script to make all but the first paragraph tiny.
So I turned to jQuery to wrap the first letter of the first paragraph with a <span> tag that I could style however I wanted. I found inspiration for this script on the Learning jQuery website, but I couldn’t find a pre-made script that would do exactly what I needed. So here is my script, hopefully it will help someone else out.
Stylesheet
.init-cap {
font-size: 1.5em; /* Set the size of the raised letter */
line-height: 1.2em; /* Adjust the line spacing to match the rest of the text */
}
Javascript
$(document).ready(function() {
$(’.cap p:first’).each(function() {
var text = $(this).html();
var first_letter = text.substr(0,1);
if ( /[a-zA-Z]/.test(first_letter) ) {
$(this).html(’<span class="init-cap">’ + first_letter + ‘</span>’ + text.slice(1));
}
});
});
What we are doing is selecting the first paragraph inside each element with the class “cap” applied to it. We then chop the first letter off that paragraph, check to be sure it is really a letter (rather than a tag, for instance), and add it back on wrapped inside a <span> tag. By adjusting the CSS, this could easily be used for drop-caps, as well.
Comments: