CSS

::selection

::selection

::selectionCSS伪元件适用样式已被突出显示由用户(例如,用鼠标)一个文档的所述部分。

::selection { color: gold; background: red; }

只有一小部分css属性可以与::selection伪元素:

  • color

  • background-color

  • cursor

  • outline

  • text-decoration

  • text-emphasis-color

  • text-shadow

特别要注意的是,background-image被忽视了。

语法

/* Firefox syntax */ ::-moz-selection ::selection

HTML

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

CSS

/* Make selected text gold on a red background */ ::-moz-selection { color: gold; background: red; } ::selection { color: gold; background: red; } /* Make selected text in a paragraph white on a blue background */ p::-moz-selection { color: white; background: blue; } p::selection { color: white; background: blue; }

结果

规范

SpecificationStatusComment
CSS Pseudo-Elements Level 4The definition of '::selection' in that specification.Working DraftInitial definition

注意:尽管::selection存在于CSS选择器级别3的草案中,但是在候选推荐阶段被删除,因为它的行为没有被规定(特别是嵌套元素)并且没有实现互操作性(基于W3C Style邮件列表中的讨论)。该::selection伪元素被带回在伪元素4级。

浏览器兼容性

注:text-shadow::selection由Chrome、Safari和Firefox 17+支持。

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1(Yes)1.0 -moz199.51.1

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support??(Yes)????