【问题标题】:Edit colour of text within CSS content编辑 CSS 内容中文本的颜色
【发布时间】:2021-08-22 17:41:55
【问题描述】:

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

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

我想将“请注意”涂成红色,但保持其他文本与默认颜色相同。这可能吗?

【问题讨论】:

  • 这是不可能的。您不能更改部分伪元素的颜色。

标签: css colors css-content


【解决方案1】:

将文本包装在一个 span 标签中,这样您就可以赋予它自己的风格。

如果我有这样的 HTML:

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

我想突出显示子字符串“NOTE:”,我需要像这样调整我的 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
}

【讨论】:

  • 您不能在 CSS 伪元素内容属性值中使用这种 HTML。
  • @AHaworth 正确。仅使用 CSS 是不可能的。
【解决方案2】:

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

我使用的一种方法是使内容等宽,并在需要引起用户注意的字符上放置背景颜色。例如,此 sn-p 仅将黄色放在“请注意”字后面:

.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;
}
&lt;div class="info"&gt;info div&lt;/div&gt;

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

.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;
    }
}
&lt;div class="info"&gt;info div&lt;/div&gt;

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

【讨论】:

  • 非常感谢这对我有用。我选择了第二种方法,作为奖励,我能够将字体系列更改为我的默认值,而且似乎效果很好!
猜你喜欢
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 2014-09-26
相关资源
最近更新 更多