Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use just CSS to change color and font size of first letter of every word

Tags:

jquery

css

As in the question title, is it possible to change the color and font size of the first letter of every word. For example, like the following image:

enter image description here

Is it possible to do this with only CSS? I could use jQuery but only if it is not possible with a pure CSS or CSS3 solution.

like image 457
GajendraSinghParihar Avatar asked Sep 21 '12 13:09

GajendraSinghParihar


3 Answers

You can produce text in small caps with every word capitalized using this CSS:

h1 {
    font-variant: small-caps;
    text-transform: capitalize;
}

But you won't be able to change the color of the initial letters using CSS alone; you're going to have to use jQuery to add span elements to your text then style those elements. Something like this:

$('h1').html(function() {
    // Very crude regex I threw together in 2 minutes
    return $(this).text().replace(/\b([a-z])/gi, '<span class="caps">$1</span>')
});

With this CSS:

h1 {
    font-variant: small-caps;
    text-transform: capitalize;
}

h1 .caps {
    color: red;
}
like image 68
BoltClock Avatar answered Nov 08 '22 01:11

BoltClock


JSFiddle

Here you go -

<p class="each-word">First letter of every word is now red!</p>

.first-letter {
    color: red;
  }

window.onload = function(){
  var elements = document.getElementsByClassName("each-word")
  for (var i=0; i<elements.length; i++){
    elements[i].innerHTML = elements[i].innerHTML.replace(/\b([a-z])([a-z]+)?\b/gim, "<span class='first-letter'>$1</span>$2")
  }
}
like image 21
Dipak Avatar answered Nov 08 '22 00:11

Dipak


Use the psedo-element :first-letter , like:

.word:first-letter
{ 
   font-size:200%;
   color:#8A2BE2;
}

As the comments suggest, this needs each word to be in its own element, eg. <span>

But this is the closer you'll get to what OP wants in pure CSS.

like image 1
Nelson Avatar answered Nov 07 '22 23:11

Nelson