我想要一些具有不同颜色边框且具有重复图案的嵌套 div。
例如我可以有 5 种颜色,红、蓝、绿、黄、橙
我想得到与下面相同的效果,但是只使用基于 DIV 位置的 css 而不是实际必须在每个 div 上添加类名
<div class="redBorder">
<div class="blueBorder">
<div class="greenBorder">
<div class="yellowBorder">
<div class="orangeBorder">
<div class="redBorder">
<div class="blueBorder">
<div class="greenBorder">
<div class="yellowBorder">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
这与此处发布的问题类似,但我想指定每个第 n 步使用的颜色。
Repeating a set of colors on nested divs with CSS
我已根据给出的示例尝试了以下...
<style>
div {
border: 2px solid #ccc;
border-top: 5px solid #ccc;
padding: 5px;
padding-top: 50px;
border-radius: 5px;
}
div {
border-color: linear-gradient(
to right,
red calc(0 * 100% / 4) calc(1 * 100% / 4),
blue calc(1 * 100% / 4) calc(2 * 100% / 4),
green calc(2 * 100% / 4) calc(3 * 100% / 4),
yellow calc(3 * 100% / 4) calc(4 * 100% / 4)
)
calc(var(--x) * 100% / 3) 0/400% 100%;
}
</style>
使用以下标记,但这没有用
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
最佳答案
如果您可以使用不同的元素交替嵌套,您可以尝试使用 CSS 变量进行如下操作。我们需要不同的元素才能在结合两个变量的每个级别上递增一个变量。 (相关:Can a recursive variable be expressed in css?)
我考虑过 4 种颜色,但您可以轻松地扩展到任何数量:
:root {
--p:0;
--x:0;
}
.first,
.first span,
.first div{
padding:10px;
border:5px solid transparent;
background:
linear-gradient(white,white) padding-box, /* Color only the padding box*/
/* N = 4*/
repeating-linear-gradient(
red 0 calc(100%/4),
blue calc(1*100%/4) calc(2*100%/4),
green calc(2*100%/4) calc(3*100%/4),
purple calc(3*100%/4) calc(4*100%/4))
0 calc(var(--p)*100%/3)/ /* 0 var(--p)*100%/(N-1) */
100% 400% /* Width:100% height:N*100% */
border-box; /* Color the border area */
}
.first span {
--p:calc(var(--x) + 1);
display:block;
}
.first div {
--x:calc(var(--p) + 1);
background-position:0 calc(var(--x)*100%/3); /* 0 var(--x)*100%(N-1) */
}
<div class="first">
<span>
<div>
<span>
<div>
<span>
<div>
<span>
<div>
</div>
</span>
</div>
</span>
</div>
</span>
</div>
</span>
</div>
也可以保留同一个元素,用一个类来区分:
:root {
--p:0;
--x:0;
}
.first,
.first *{
padding:10px;
border:5px solid transparent;
background:
linear-gradient(white,white) padding-box, /* Color only the padding box*/
/* N = 4*/
repeating-linear-gradient(
red 0 calc(100%/4),
blue calc(1*100%/4) calc(2*100%/4),
green calc(2*100%/4) calc(3*100%/4),
purple calc(3*100%/4) calc(4*100%/4))
0 calc(var(--p)*100%/3)/ /* 0 var(--p)*100%/(N-1) */
100% 400% /* Width:100% height:N*100% */
border-box; /* Color the border area */
}
.first div.x {
--p:calc(var(--x) + 1);
}
.first div:not(.x) {
--x:calc(var(--p) + 1);
background-position:0 calc(var(--x)*100%/3); /* 0 var(--x)*100%(N-1) */
}
<div class="first">
<div class="x">
<div>
<div class="x">
<div>
<div class="x">
<div>
<div class="x">
<div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
关于html - 如何创建嵌套 div 的重复彩虹是 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58817265/