跳到主要内容

CSS 文本选择颜色

阐述

选择颜色是指选中文字时它的颜色和背景颜色。我们可以通过 ::selection 伪元素来设置这些颜色。

实例

<style>
p::selection {
color: black;
background-color: yellow;
}
</style>

<p>
This paragraph has <em>some emphasized text</em>, in the middle.
</p>

性质

相关内容

不同于 CSS 字体颜色和 CSS 背景颜色,选择颜色是不继承的(尽管它按标准应该是可继承的)。我们可以通过 CSS 变量来解决这个问题:

<style>
::selection {
color: var(--selection-color);
background-color:
var(--selection-background);
}

html {
/*
Define global defaults
for selection colors…
*/
--selection-color:
hsl(25deg 100% 20%);
--selection-background:
hsl(55deg 100% 60%);
}

figure {
/*
…But then override those values
for specific parts of the page!
*/
--selection-color: hsl(0deg 0% 0%);
--selection-background:
hsl(333deg 100% 50%);
}
</style>

<p>
Lorem Ipsum is simply <em>dummy text of the printing and typesetting industry</em>. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>

<figure>
<img
alt="Handsome-looking dog"
src="/cfj-mats/article-image-spot.jpg"
/>
<figcaption>
Try selecting this text! The styles are different
</figcaption>
</figure>

参考文献