How to Capitalize first letter only using CSS in each case

情到浓时终转凉″ 提交于 2019-12-03 11:27:25

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

zurfyx

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

Neal

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/

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;*

}
Ravi Joon

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!