如何使伪类颜色匹配元素所应用背景类的颜色?
解决方案
要让::before伪类的边框颜色与当前应用的背景类颜色匹配,你可以借助**CSS自定义属性(变量)**来实现,具体步骤如下:
1. 为每个背景类定义对应颜色变量
在设置背景色的同时,给每个背景类添加一个自定义属性,用来存储当前背景色的值:
/* 基础test-div样式,必须添加position: relative让伪类相对它定位 */ .test-div { position: relative; /* 其他基础样式 */ } /* 亮金色背景类 */ .test-div.test-div-bg-bright-gold { background-color: #ffd700; --bg-color: #ffd700; /* 定义匹配的颜色变量 */ } /* 深蓝色背景类 */ .test-div.test-div-bg-dark-blue { background-color: #00008b; --bg-color: #00008b; /* 定义匹配的颜色变量 */ }
2. 修改伪类代码使用变量
把::before伪类中border-right的颜色值替换为自定义变量var(--bg-color):
.test-div::before { content: ''; position: absolute; top: 0; left: 0; border-top: 100px solid white; border-right: 100px solid var(--bg-color); /* 使用变量匹配背景色 */ width: 0; }
这样一来,当你给test-div添加不同的背景类时,伪类的边框颜色会自动跟随背景色变化,无需单独为每个背景类编写伪类样式。
内容的提问来源于stack exchange,提问作者Herro2689
相关产品推荐
相关产品推荐

