gpt4 book ai didi

css - 合并从不同类继承的背景

转载 作者:行者123 更新时间:2023-12-04 10:12:01 25 4
gpt4 key购买 nike

我想要几个类(例如 redgreenblue )在元素旁边创建一个小的彩色方块,例如

div { display: inline-block; margin: 20px; width: 20px; height: 20px; border: 1px dashed black; }
.square::before { position: absolute; display: block; margin-left: -10px; width: 8px; height: 20px; content: ''; }
.blue::before { background: linear-gradient(to bottom, blue 8px, transparent 8px); }
.green::before { background: linear-gradient(to bottom, transparent 8px, green 8px, green 16px, transparent 16px) }
现在当我使用 <div class="square blue"></div>我得到这个结果
enter image description here
并使用 <div class="square green"></div>产生
enter image description here
现在我想得到这个结果
enter image description here
通过使用 <div class="square blue green"></div> ,但绿色规则覆盖蓝色规则。我知道多个 css 背景,但我想使用至少 6 个不同方块的组合并为此创建 63 条规则有点蛮力。
有没有办法在不添加隐藏的 HTML、通过 javascript 构建渐变或编写指数数量的 css 规则的情况下实现这一目标?

最佳答案

CSS 变量和一个伪元素可以做到这一点。然后使用内联样式分配颜色以获得您想要的任何组合或使用预定义的类:

div {
display: inline-block;
margin: 20px;
width: 40px;
height: 60px;
border: 1px dashed black;
position:relative;
}

.square::before {
content: '';
position: absolute;
top:0;
bottom:0;
right:105%;
width: 8px;
background-image:
linear-gradient(var(--c1,transparent),var(--c1,transparent)),
linear-gradient(var(--c2,transparent),var(--c2,transparent)),
linear-gradient(var(--c3,transparent),var(--c3,transparent)),
linear-gradient(var(--c4,transparent),var(--c4,transparent)),
linear-gradient(var(--c5,transparent),var(--c5,transparent)),
linear-gradient(var(--c6,transparent),var(--c6,transparent));
background-size:100% calc(100%/6);
background-position:
0 calc(0*100%/5),
0 calc(1*100%/5),
0 calc(2*100%/5),
0 calc(3*100%/5),
0 calc(4*100%/5),
0 calc(5*100%/5);
background-repeat:no-repeat;
}

.blue {--c1:blue;}
.red {--c2:red;}
.green {--c3:green;}
.yellow {--c4:yellow;}
.purple {--c5:purple;}
.black {--c6:black;}
<div class="square blue"></div>

<div class="square blue green red"></div>

<div class="square blue yellow purple red"></div>

<div class="square" style="--c5:black;--c4:red;--c3:blue;"></div>

<div class="square yellow purple" style="--c1:black;--c2:red;--c3:blue;--c6:red"></div>

关于css - 合并从不同类继承的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61293615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com