CSS Handbook · 伪元素

第三章 / 3.3 其他伪元素

第三章 · 3.3 节

其他伪元素


除了 ::before/::after 与排版类伪元素,浏览器还为一些特定场景开放了专属的伪元素接口,覆盖文本选中、表单占位符、列表符号乃至原生对话框的背景遮罩。

::selection

自定义用户用鼠标拖选文本时的高亮样式,只支持 color、background-color、text-shadow 等少量属性。

::selection {
  background: #d3985a;
  color: #ffffff;
}
试一试:用鼠标选中下面这段文字

选中我看看效果——本教程站点全局也应用了这一自定义样式。

::placeholder

定制表单占位文字的样式,注意它的默认颜色对比度较低,适当调整能提升可读性,但不宜与真实输入内容的颜色过于接近。

input::placeholder {
  color: #a39fb5;
  font-style: italic;
}
效果预览

::marker

作用于列表项 <li> 的项目符号或序号本身,无需再用 list-style: none + 伪元素模拟,即可直接改变颜色、大小甚至替换内容。

li::marker {
  color: #8a5a2e;
  font-size: .9em;
}
li.important::marker {
  content: "★ ";
}
效果预览
  • 选择器
  • 伪元素

::backdrop

作用于以全屏模式或原生 <dialog> 弹出的元素背后的遮罩层,让我们无需额外的遮罩 div 即可定制蒙层颜色与模糊效果。

dialog::backdrop {
  background: rgba(38,35,58,.5);
  backdrop-filter: blur(2px);
}

::file-selector-button

作用于 <input type="file"> 内置的"选择文件"按钮,是少数几个可以直接美化原生表单控件子部件的接口之一。

input[type="file"]::file-selector-button {
  background: #3f5d54;
  color: #fff;
  border: none;
  padding: 6px 14px;
  border-radius: 4px;
}

Chapter 3 · Section 3.3

Other Pseudo-elements


Besides ::before/::after and the typography pseudo-elements, browsers expose dedicated pseudo-element interfaces for specific scenarios, covering text selection, form placeholders, list markers, and even the backdrop of native dialogs.

::selection

Customizes the highlight style when the user selects text by dragging with the mouse; only a few properties such as color, background-color and text-shadow are supported.

::selection {
  background: #d3985a;
  color: #ffffff;
}
Try it: select the text below with your mouse

Select me to see the effect — this tutorial site also applies this custom style globally.

::placeholder

Customizes the style of form placeholder text. Note that its default color has low contrast; adjusting it can improve readability, but it should not be too close to the color of actual input content.

input::placeholder {
  color: #a39fb5;
  font-style: italic;
}
Preview

::marker

Targets the bullet or the number of a list item <li> itself, letting you directly change its color, size, or even replace its content — no need for list-style: none plus a pseudo-element workaround.

li::marker {
  color: #8a5a2e;
  font-size: .9em;
}
li.important::marker {
  content: "★ ";
}
Preview
  • Selectors
  • Pseudo-elements

::backdrop

Targets the backdrop layer behind elements shown in fullscreen mode or via the native <dialog>, letting us customize the overlay color and blur without an extra backdrop div.

dialog::backdrop {
  background: rgba(38,35,58,.5);
  backdrop-filter: blur(2px);
}

::file-selector-button

Targets the built-in "Choose file" button of <input type="file">, one of the few interfaces that let you directly style a sub-part of a native form control.

input[type="file"]::file-selector-button {
  background: #3f5d54;
  color: #fff;
  border: none;
  padding: 6px 14px;
  border-radius: 4px;
}