I\'m attempting to either use jQuery, CSS or PHP to increase the font size of the first letter of each word in a string. For example, I\'m going to have a title in h1 tags
I couldn't get :first-letter
to work, but here's a possible solution, assuming the <h1>
does not contain additional tags or entities:
$('h1').html(function(i,html){
return html.replace(/(\S)(\S*)/g, '<span class="FirstLetter">$1</span>$2');
});
CSS:
.FirstLetter {color:green}
A possible benefit here is that this should work on all browsers.
The regex is fairly simple: \S
stands for a non-whitespace character. It matches word by word and captures the first letter in each word in the first group ($1
), and the rest of the letters in the second group ($2
), for an easy replace.
Working example: http://jsbin.com/ufovi4
The easiest way is probably just straight CSS, though it creates a bit extra markup for you to write. JQuery would end up making the same amount of extra markup, though, with extra overhead, and would fail without JS support. h1.dropcaps div{ float:left; } h1.dropcaps div:first-letter { font-size : 300%; font-weight : bold; }
<h1 class="dropcaps"><div>Your</div> <div>text</div> <div>here</div>
UPDATE: It turns out :first-letter does not work inside an inline element in some browsers.
The trick to fix this is to put them in divs, and float the divs. I have revised my markup. http://jsfiddle.net/MBZaw/
This will work. Just set in your CSS to h1 span {font-size: 125%}
, or whatever.
$('h1').each(function(){
var $this = $(this);
var words = $this.text().split(' ');
var newHtml = '';
for (var i = 0; i < words.length; i++) {
newHtml += '<span>' + words[i].substring(0, 1) + '</span>' + words[i].substring(1) + ' ';
}
$this.html(newHtml);
});
Here is the JSfiddle
var h1 = $('h1'),
words = h1.html().split(' '),
withCaps = '';
for (var i = 0; i < words.length; i++)
withCaps += '<span>' + words[i].substring(0, 1).toUpperCase() + '</span>' + words[i].substring(1) + ' ';
h1.html(withCaps);
$(document).ready(function() {
var words = $('h1').text().split(' ');
var html = '';
$.each(words, function() {
html += '<span style="font-size:200%">'+this.substring(0,1)+'</span>'+this.substring(1) + ' ';
});
$('h1').html(html);
});
Here's an example of it in action: http://jsfiddle.net/hCvsu/1/
Ajma solution works if you have only one h1 in your page.
This works for all h1 :
$('h1').each(function() {
var jqt = $(this);
var txt = jqt.text();
jqt.html('<span style="font-size:200%">'+txt.substring(0,1)+'</span>'+ txt.substring(1));
});
Possible improvements : instead of a span with a style, create a span with a class and do font-size:200% in CSS.
Possible problems : if your h1 contains other tags (which it should not!) those tags are lost, only text is retained.
Hope it helps, Simone