Cyclic css rules for alternating background color of nested elements

后端 未结 1 920
灰色年华
灰色年华 2021-01-20 09:41

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

相关标签:
1条回答
  • 2021-01-20 10:25

    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>

    0 讨论(0)
提交回复
热议问题