You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS中:first-letter伪类覆盖::selection自定义选中样式问题问询

解决:first-letter伪类覆盖::selection自定义选中颜色的问题

当同时使用:first-letter伪类和::selection伪类时,首字母的自定义选中颜色会被:first-letter覆盖,调整两者的代码顺序后问题依然存在,这并非选择器优先级导致的问题。

复现代码

CSS代码

.test::selection {
  background-color: green;
  color: white;
}

.test:first-letter {
  text-transform: uppercase;
}

HTML代码

<div class='test'>this is a test</div>

问题原因

:first-letter伪元素会生成独立的格式化上下文,文本被选中时,::selection的样式无法自动继承到这个伪元素上,因此首字母的选中样式会回退到浏览器默认值,而非自定义的::selection样式。

解决方案

需要单独为:first-letter的选中状态指定样式,通过组合first-letter::selection伪类来覆盖默认行为,让首字母也应用自定义的选中样式。

修改后的CSS代码如下:

/* 全局文本选中样式 */
.test::selection {
  background-color: green;
  color: white;
}

/* 首字母大写样式 */
.test:first-letter {
  text-transform: uppercase;
}

/* 首字母的选中样式 */
.test:first-letter::selection {
  background-color: green;
  color: white;
}

也可以简化为合并选择器的写法,减少重复代码:

.test::selection,
.test:first-letter::selection {
  background-color: green;
  color: white;
}

.test:first-letter {
  text-transform: uppercase;
}

内容的提问来源于stack exchange,提问作者raz-ezra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 13:45:28