15

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."

4

5 回答 5

37

您应该能够使用:first-letter伪元素:

.fl {
 display: inline-block;
}

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

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

产量:

更好的东西

于 2013-07-03T14:28:36.950 回答
7

单独使用 CSS 是不可能的,但您可以使用 Javascript 或 PHP 来实现。

PHP中

ucwords()

Javascript中

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

使用 JavaScript 从将字符串转换为标题大小写中提取

于 2013-07-03T14:20:10.233 回答
6

您可以尝试结合使用这个答案和一些 javascript(使用 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;
}

演示:http: //jsfiddle.net/maniator/ZHhqj/

于 2013-07-03T14:42:47.400 回答
4

为什么不直接在 css 中使用 :first-letter 伪元素?

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

}

h2{

*your general code for h2 goes here;*

}
于 2015-08-11T08:50:19.257 回答
-1

是的,CSS 在这里没有帮助。欢迎来到 JavaScript 的世界,一切皆有可能。

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>
于 2015-12-01T07:53:12.240 回答