Kabir
Kabir

Reputation: 2156

How to Capitalize first letter only using CSS in each case

I want to Capitalize first letter only and other should be small using CSS

String is:

SOMETHING BETTER 
sOMETHING bETTER
Something better

but the result should be

Something Better

Is this possible using CSS? To Capitalize first letter I am using

text-transform: capitalize;

But not able to capitalize in each case. "I want to use CSS because in my application it has written every where hard coded but a class has been called everywhere."

Upvotes: 18

Views: 64118

Answers (5)

Ravi Joon
Ravi Joon

Reputation: 44

Yes, CSS is no help here. Welcome to the world of JavaScript, where anything is possible.

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")
  }
}



  .first-letter {
    color: red;
  }



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

Upvotes: -1

Abibi8
Abibi8

Reputation: 41

Why dont you just use the :first-letter pseudo element in css?

h2:first-letter{
text-transform: uppercase;

}

h2{

*your general code for h2 goes here;*

}

Upvotes: 4

Naftali
Naftali

Reputation: 146310

You can try a combination of this answer and some javascript (using jQuery)

HTML:

<div class='capitalize'>
    SOMETHING BETTER 
    SOMETHING BETTER 
    SOMETHING BETTER 
</div>

JAVASCRIPT:

$('.capitalize').each(function(){
    var text = this.innerText;
    var words = text.split(" ");
    var spans = [];
    var _this = $(this);
    this.innerHTML = "";
    words.forEach(function(word, index){
        _this.append($('<span>', {text: word}));
    });
});

CSS:

.capitalize {
    text-transform: lowercase;
}

.capitalize span {
    display: inline-block;
    padding-right: 1em  
}

.capitalize span:first-letter {
    text-transform: uppercase !important;
}

Demo: http://jsfiddle.net/maniator/ZHhqj/

Upvotes: 7

zurfyx
zurfyx

Reputation: 32767

It is not possible with CSS alone but you can do it with Javascript or PHP for example.

In PHP

ucwords()

And in Javascript

function toTitleCase(str){
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

Extracted from Convert string to title case with JavaScript

Upvotes: 8

mzmm56
mzmm56

Reputation: 1292

you should be able to use the :first-letter pseudo element:

.fl {
 display: inline-block;
}

.fl:first-letter {
 text-transform:uppercase;
}

<p>
 <span class="fl">something</span> <span class="fl">better</span>
</p>

yields:

Something Better

Upvotes: 41

Related Questions