如何更改伪类颜色以匹配另一个类的颜色?

问题描述 投票:0回答:2

我为网页创建了一个“块”,例如名为“test-div”的网页。

测试 div 还添加了一个额外的类来更改其背景颜色,即。

test-div test-div-bg-bright-gold 
test-div test-div-bg-dark-blue

等等

我的 test-div 之前也有一个伪类来剪切左上角边框,我需要它的颜色来匹配所应用的 bg 类。之前的 CSS 看起来像这样 -

test-div::before {
     content: '';
    position: absolute;
    top: 0; left: 0;
    border-top: 100px solid white;
    border-right: 100px solid var(--COLORTOMATCHTHEBGCLASSGOESHERE?);
    width: 0;
   }

多年来我一直在尝试弄清楚如何做到这一点,因此我们将不胜感激。

谢谢!

css pseudo-class
2个回答
1
投票

您可以在颜色修改类中设置

var
值。这样,变量就可以应用于 div 的
background-color
border
元素的
pseudo

.test-div {
  width: 200px;
  height: 300px;
  position: relative;
  background: var(--background-color);
}

.test-div--blue {
  --background-color: blue;
}

.test-div--gold {
  --background-color: gold;
}

.test-div::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border-top: 100px solid white;
  border-right: 100px solid var(--background-color);
  width: 0;
}
<div class="test-div test-div--blue">
</div>

<div class="test-div test-div--gold">
</div>


0
投票

CSS 自定义属性(又名变量)是继承属性,所以你可以这样做:

.card {
  --card-bg-color: white;
  background-color: var(--card-bg-color);
  padding: 8px;
  border: 1px solid gray;
  margin-block: 100px;
  position: relative;
}

.card::before {
  content: "";
  position: absolute;
  top: 0; left: 0;
  border-top: 100px solid white;
  border-right: 100px solid var(--card-bg-color);
  width: 0;
}

.card.error {
  --card-bg-color: red;
}
<div class="card"></div>
<div class="card error"></div>

当您覆盖自定义属性的值时,它将由其子级(包括伪元素)继承。

© www.soinside.com 2019 - 2024. All rights reserved.