CSS ::selection伪元素不生效 无法设置指定选中背景色问题求助
问题根因
- 选择器写法错误:你把
!important写在了::selection伪元素选择器后面,该修饰符只能附加在CSS属性值末尾,写在选择器上完全不生效。 - 样式继承冲突:
-webkit-background-clip: text、-webkit-text-fill-color: transparent以及动画属性都会被::selection伪元素继承,导致选中态的背景依然沿用文字的渐变和动画效果,透明的文字填充也会让选中的文字看起来像被隐藏了。
解决方案
针对带渐变的.rgb类单独配置选中态,覆盖继承的冲突属性即可,修改后的CSS代码如下:
@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap'); * { margin: 0; padding: 0; background-color: #1e1e1e; font-family: 'Montserrat', sans-serif; } .rgb { position:fixed; background: linear-gradient(to right, #008AFF, #00FFE7); animation:animate 10s forwards infinite; -webkit-background-clip: text; -webkit-text-fill-color: transparent; } /* 普通文本选中样式 */ ::selection { background: red; color: white; } /* 渐变文字单独配置选中样式 */ .rgb::selection { -webkit-text-fill-color: white; /* 覆盖透明填充,显示选中文字 */ background: red !important; /* 固定选中背景色 */ -webkit-background-clip: initial; /* 取消背景裁剪到文字的设置 */ animation: none; /* 停止选中区域的渐变动画 */ filter: none; /* 取消色相旋转滤镜效果 */ } @keyframes animate { 0%, 100% { filter:hue-rotate(0deg); } 50% { filter:hue-rotate(360deg); } }
HTML代码无需改动,修改后Chrome环境下即可实现渐变文字正常选中,选中背景固定为红色、文字为白色的效果,完全保留原有的RGB渐变文字动画。
内容的提问来源于stack exchange,提问作者Monke
相关产品推荐
相关产品推荐

