CSS 伪元素: ::marker 自定义列表序号

::marker

伪元素 ::marker,可作用在任何设置了 display: list-item 的元素或伪元素上,例如<li>和<summary>。

/**
<ul>
  <li>Peaches</li>
  <li>Apples</li>
  <li>Plums</li>
</ul>
*/
ul li::marker {
  color: red;
  font-size: 1.5em;
}

但是,对于::marker伪元素内的样式,目前只允许使用:

    all font properties -- 所以字体属性相关 color -- 颜色值 the content property -- content 内容,类似于 ::before 伪元素 的 content,用于填充序号内容 text-combine-upright (en-US), unicode-bidi and direction properties -- 文档书写方向相关

浏览器兼容性:

其他探索

1. 动态变化

::marker 动态的改变,可以搭配 :hover 实现鼠标悬停变换。

li {
  color: #000;
  transition: .2s all;
}
li:hover {
  color: #ff6000;
}
li::marker {
  content: 😩;
}
li:hover::marker {
  content: 😁;
}

2. 搭配 CSS 计数器 counter

::marker 也有 content 样式属性,由于 content 的 value 是可以做简单的字符串加法操作的。

因此,利用 ::marker 和 CSS 计数器 counter-increment 实现一个自动计数且 h3 前面带一个特定符号的有序列表:

h3 {
  counter-increment: h3;
  display: list-item;
}

h3::marker {
  display: list-item;
  content: "#" counter(h3) " ";
  color: lightsalmon;
  font-weight: bold;
}

body {
  counter-reset: h3;
  line-height: 1.4;
  font-family: system-ui;
  margin: 3rem;
}
经验分享 程序员 微信小程序 职场和发展