How to Capitalize first letter only using CSS in each case

后端 未结 5 1832
礼貌的吻别
礼貌的吻别 2021-02-13 04:10

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

String is:

SOMETHING BETTER 
sOMETHING bETTER
Something bett         


        
相关标签:
5条回答
  • 2021-02-13 04: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>
    
    0 讨论(0)
  • 2021-02-13 04:55

    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

    0 讨论(0)
  • 2021-02-13 04:57

    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

    0 讨论(0)
  • 2021-02-13 04:57

    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/

    0 讨论(0)
  • 2021-02-13 05:05

    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;*
    
    }
    
    0 讨论(0)
提交回复
热议问题