微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

编辑 CSS 内容中文本的颜色

如何解决编辑 CSS 内容中文本的颜色

我想更改某些文本的颜色,但该文本位于 CSS 属性内容”中。有没有办法选择特定的单词并为它们着色?

例如这里是我的代码 .info:before { content: "PLEASE NOTE: this would be something that the user has to 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>

另一种为您提供所需红色字符的方法是使用文本作为剪贴蒙版,并在前两个单词下方将背景设为红色,否则为黑色: enter image description here

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

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

,

将文本包裹在 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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。