There are sections with alternating background and text colors, as it is more convenient to set styles so as not to prescribe them for each section.

There is a class with common section styles, I only have to add one more class to odd sections that will set the background and text color.

Are there any other suggestions or options?

    1 answer 1

    As an option:

    Use the pseudo-class :nth-child . Read more ...
    Learn more about support in different browsers ...

     .block > .row >.item:nth-child(odd) { background: #fff; } .block > .row >.item:nth-child(even) { background: #000; } .block > .row-o >.item:nth-child(even) { background: #fff; } .block > .row-o >.item:nth-child(odd) { background: #000; } .item { width: 25%; height: 150px; float: left; } 
     <div class="block"> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row-o"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div class="row-o"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> 

    UPD

     .container { width: 33.3333%; float: left; height: 150px; background: green; } .wrapper > section:nth-child(even) > .container { background: red; } 
     <div class="wrapper"> <section> <div class="container"> </div> </section> <section> <div class="container"> </div> </section> <section> <div class="container"> </div> </section> </div> 

    • 2
      :nth-child(2n) or :nth-child(2n + 1) will work in 97% of browsers, starting with IE9 - andreymal
    • @andreymal, it's good, something I didn’t look there :) - user242433
    • Thank you) this option was also considered, but there was a problem with the structure and somehow it did not work correctly, now I fixed everything well. But for some reason the color of the font does not want to change, apparently it is somewhere reassigned further or the specificity is higher, although even with the addition of! Important nothing changes. Okay, I will understand further) - kost1k
    • @Cactus, there is still a small question if I have the following structure <div class = "wrapper"> <section> <div class = "container"> </ div> </ section> <section> <div class = "container "> </ div> </ section> <section> <div class =" container "> </ div> </ section> </ div> and you need to set the background for the container, then this will not work? - kost1k
    • @ kost1k, it seemed to work :) Updated the answer. And if you said in the previous comment that you cannot change the color, then try ctrl + f5 in chrome. Update cache, sometimes it helps :) - user242433