Cyclic css rules for alternating background color of nested elements

Viewed 224

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.

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>

Is there another way to do it with CSS?

1 Answers

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>

Related