循环CSS规则,可交替使用嵌套元素的背景色 [英] Cyclic css rules for alternating background color of nested elements

查看:114
本文介绍了循环CSS规则,可交替使用嵌套元素的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态页面,用户可以在其中根据需要在其他div中添加尽可能多的div。每个div都有背景色,我希望背景色每3 div重复一次。

I have a dynamic page where the user can add as many div inside other div as he wants. Each div has a background color and I want the background color to repeat itself every 3 divs.

当前,我正在编写这样的CSS规则

Currently, I'm writing the css rules like this

div {
  padding-top: 20px;
  margin-left: 10px;
}

div {
  background-color: blue;
}

div>div {
  background-color: red;
}

div>div>div {
  background-color: green;
}

div>div>div>div {
  background-color: blue;
}

div>div>div>div>div {
  background-color: red;
}

div>div>div>div>div>div {
  background-color: green;
}

div>div>div>div>div>div>div {
  background-color: blue;
}


/* and it continues... */

<div>
  <div>
    <div>
      <div>
        <div>
          <div>
            <div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

还有另一个

推荐答案

这不是直接的答案,但是如果您可以嵌套其他元素(div,section例如)这是一个如何使用纯CSS的想法。诀窍是使用CSS变量控制背景位置,然后为每个孩子增加它,以便将背景移到下一个颜色。您需要替换元素才能实现增量,其中一个元素将具有循环,将无法使用。

This is not a direct answer but in case you can nest alternate elements (div, section for example) here is an idea how you can do with pure CSS. The trick is to use CSS variable to control background-position and you increment it for each child so you move the background to the next color. You need alternate elements to be able to achieve the incrementation, with one element we will have cycle and it won't work.

:root {
 --i:1;
 --j:1;
}

div,section {
  padding-top: 20px;
  margin-left: 10px;
  background: 
    repeating-linear-gradient(to bottom, 
      blue 0, blue calc(100%/3), 
      red calc(100%/3), red calc(2*100%/3), 
      green calc(2*100%/3), green 100%);
  background-size:100% 300%;
}
section {
 --j:calc(var(--i) + 1);
 background-position:0 calc(var(--j) * 100%);
}

div {
 --i:calc(var(--j) + 1);
 background-position:0 calc(var(--i) * 100%);
}

<div>
  <section>
    <div>
      <section>
        <div>
          <section>
            <div>

            </div>
          </section>
        </div>
      </section>
    </div>
  </section>
</div>

这篇关于循环CSS规则,可交替使用嵌套元素的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆