编辑 CSS 内容中的文本颜色

Edit colour of text within CSS content

我想更改一些文本的颜色,但文本在 CSS 属性 'content' 中。有没有办法 select 特定的词并给它们着色?

例如这里是我的代码 .info:before { content: "PLEASE NOTE: this would be something that the user has to note... "; }

我想将 'PLEASE NOTE' 涂成红色,但让其他文本与默认颜色相同。这可能吗?

将文本包裹在 span 标签中,这样您就可以赋予它自己的样式。

如果我有 HTML 这样的:

<p class="info">NOTE: The stories and information posted here are artistic works of fiction and falsehood.</p>

我想突出显示子字符串“注意:”,我需要像这样调整我的 HTML:

<p class="info"><span>NOTE:</span> The stories and information posted here are artistic works of fiction and falsehood.</p>

然后我可以使用以下 CSS 将其设为红色:

p.info span {
    color:red
}

虽然您无法按照您希望的方式设置伪元素内容中文本的格式,但有多种突出显示方式可能会有所帮助,具体取决于您的用例。

我用过的一个方法是让内容等宽,并在需要引起用户注意的字符上放置背景色。例如,此代码段仅在 'Please note' 字词后面加上黄色:

.info:before {
  content: "PLEASE NOTE: this would be something that the user has to note... ";
  background-image: linear-gradient(to right, yellow 0, yellow 12ch, transparent 12ch, transparent 100%);
  font-family: monospace;
}
<div class="info">info div</div>

另一种给你想要的红色字符的方法是使用文本作为剪贴蒙版,并在前两个单词下面设置红色背景,否则为黑色:

.info:before {
  content: "PLEASE NOTE: this would be something that the user has to note... ";
  font-family: monospace;
  color: #000000;
  background-image: linear-gradient(to right, red 0, red 12ch, black 12ch, black 100%);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    text-fill-color: transparent;
    }
}
<div class="info">info div</div>

这给了你想要的外观(如果你能忍受内容文本的等宽)但是你必须检查你想要支持的浏览器是否可以使用文本进行剪辑。