How to color specific word in a container using CSS

后端 未结 14 1731
不思量自难忘°
不思量自难忘° 2020-12-15 05:01

Suppose I have a container:

 
This is a red apple

How to color a word \"red\" with red color? Some

14条回答
  •  别那么骄傲
    2020-12-15 05:32

    Use pseudo elements to add the coloured word and some careful positioning to cover the initial black instance. It's dirty, but it works.

    #container
    {
        position: relative;
        font-family: monospace;
        margin: 0;
        padding: 0;
        font-size: 15px;
    }
    
    #container:after
    {
        content: "red";
        color: red;
        position: absolute;
        left: 90px
    }
    

    Demo


    EDIT: Also, a variation that works with proportional fonts (but doesn't render quite so cleanly, at least for me, in Chrome):

    #container
    {
        position: relative;
        margin: 0;
        padding: 0;
    }
    
    #container:before
    {
        content: "This is a ";
        position: absolute;
        z-index: 2
    }
    
    #container:after
    {
        content: "This is a red";
        color: red;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1
    }
    

    Demo 2

提交回复
热议问题