如何使用CSS为容器中的特定单词着色 [英] How to color specific word in a container using CSS

查看:190
本文介绍了如何使用CSS为容器中的特定单词着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个容器:

 <div id="container"> This is a red apple </div>

如何用红色为单词红色"着色? 类似于(伪代码)

How to color a word "red" with red color? Something like (pseudocode)

#container:[word="red"]{
   color:red;
}

是否有可能在不引入JavaScript或不修改现有HTML的情况下在纯CSS中做到这一点?

Is it possible to do this in pure CSS without introducing JavaScript or modifying the existing HTML?

推荐答案

不是要证明一个观点,而是要回答您的问题-在没有JS的CSS中,这 是可能的: 示例

Not to prove a point, but to answer your question - this is possible in CSS without JS: Example

简而言之:我们将黑色设置为文本颜色,将红色背景设置为特定的红色字符串.我们使用-webkit-text-fill-color删除原始文本填充.使用-webkit-background-clip: text;将背景剪切到文本轮廓上,并调整红色图像的大小并将其放置在我们要着色的任何文本字符串上.

In short: we set a black background color for text color and a red background image for the specific red string. We remove the original text fill using -webkit-text-fill-color. The background is clipped to the text outline using -webkit-background-clip: text; and the red image is sized and positioned over whatever text string we want to color.

请注意: 我绝不建议将其用于任何实时网站.这仅在 webkit 中有效,因为它基于非标准的wekbit特定CSS规则.而且颜色实际上并没有绑定到彩色文本字符串上-它是完全静态的.

Please note: I would never recommend using this for any live website. This works in webkit only as it's based on non-standard wekbit-specific CSS rules. And the color is not really bound to the colored text string - it's completely static.

修改: 这是CSS:

#container {
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    background-size: 1.5em 1em;
    background-repeat: no-repeat;
    background-position: 3.4em 0;
    background-color: #000;
    background-image: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5rooor8DP9oD/2Q==);
}

这篇关于如何使用CSS为容器中的特定单词着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆