::selection

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

::selection CSS 伪元素应用于文档中被用户高亮的部分(比如使用鼠标或其他选择设备选中的部分)。

css
::selection {
  background-color: cyan;
}

允许属性

只有一小部分 CSS 属性可以用于::selection 选择器:

警告: 要特别注意的是,background-image 会如同其他属性一样被忽略。

语法

css
::selection {
  /* ... */
}

示例

HTML

html
This text has special styles when you highlight it.
<p>Also try selecting text in this paragraph.</p>

CSS

css
::-moz-selection {
  color: gold;
  background-color: red;
}

p::-moz-selection {
  color: white;
  background-color: blue;
}
css
/* 选中的文本是红色背景,金黄色的字体 */
::selection {
  color: gold;
  background-color: red;
}

/*选中的是蓝色背景,白色的字体的段落*/
p::selection {
  color: white;
  background-color: blue;
}

结果

规范

Specification
CSS Pseudo-Elements Module Level 4
# selectordef-selection

备注: ::selection CSS 伪元素选择器是 CSS 第 3 级选择器的草案,但是在被推荐使用前就被废弃。它现在在第 4 级伪元素选择器草案中。

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
::selection
Supports the text-decoration property

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.
Requires a vendor prefix or different name for use.
Has more compatibility info.