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

CSS ::first-letter样式忽略自定义选中文本selection样式问题修复

问题原因

给元素设置::first-letter样式后,浏览器会将目标首字母拆分为独立的匿名盒渲染,全局::selection选择器无法命中这个独立匿名盒内的文本,首字母选中时会直接使用浏览器默认选中样式,和其余文本的自定义选中效果产生冲突。该问题由浏览器的伪元素渲染逻辑导致,和text-transform等附加在::first-letter上的其他属性无关。

修复方法

单独为::first-letter伪元素配置对应的选中样式规则即可,Firefox 浏览器需要额外添加带-moz-厂商前缀的规则适配。

完整修正代码:

div::first-letter {
  color: red;
  text-transform: uppercase;
}

/* 全局文本选中样式 */
::-moz-selection {
  background-color: rgb(21 174 159 / 0.6) !important;
}
::selection {
  background-color: rgb(21 174 159 / 0.6) !important;
}

/* 首字母单独匹配选中样式 */
div::first-letter::-moz-selection {
  background-color: rgb(21 174 159 / 0.6) !important;
}
div::first-letter::selection {
  background-color: rgb(21 174 159 / 0.6);
}
<div>some text</div>
注意事项
  • 若页面内多个元素都使用了::first-letter样式,可直接使用通用选择器统一匹配:*::first-letter::selection,无需逐个元素单独配置
  • 厂商前缀规则不能和标准选择器合并写为逗号分隔的选择器组,否则浏览器会直接丢弃整条规则,必须分开书写
  • 该方案无需修改原有DOM结构,纯CSS即可实现全浏览器兼容,无额外副作用

内容的提问来源于stack exchange,提问作者ccc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 14:54:19