Alternate row colors between two divs

I'm not sure if this is possible in CSS, but if so, I would appreciate help.

I have HTML similar to the following:

<div class="group"></div> <div class="group"></div> <div class="group subgroup"></div> <div class="row"></div> <div class="row"></div> <div class="group"></div> <div class="group subgroup"></div> <div class="row"></div> 

Is it possible to alternate the background colors of string classes? Always start with the same color? I am having problems with this using nth-child, and I assume this is due to the group / subgroup classes.

Manual html markup in jsfiddle of an example dataset that can be returned and how it is intended for styling: http://jsfiddle.net/Qr5Za/

+4
source share
2 answers

', always starting with the same color, means that the first line after group / subgroup starts with red

If so, you can set the background-color first .row red, and the rest magenta :

 .group ~ .row { /* select all rows comes after each group */ background-color: magenta; } .group + .row { /* select and override the first row after each group */ background-color: red; } 

Jsbin demo

These selectors are called Common Word ~ and Combined Adjacent Block + , you can find more details here .

Update

All new CSS3 selectors, such as :nth-child(n) :nth-of-type(n) correspond to every element that is the n child or type of its parent .

Thus, the only way to achieve this is by .row in each block:

 <div class="group">This is a group</div> <div class="group subgroup">This is a subgroup</div> <div class="wrap"> <div class="row">This is the first row</div> <div class="row">This is the second row</div> <div class="row">This is the third row</div> <div class="row">This is the forth row</div> </div> 

And selecting odd and even lines based on their position in .wrap er (their parent):

 .row:nth-child(odd) { background-color: red; } .row:nth-child(even) { background-color: magenta; } 

JSBin Demo # 2

+4
source
 .row:nth-of-type(n) + .row:nth-of-type(even){ background: green; } .row:nth-of-type(n) + .row:nth-of-type(odd){ background: orange; } .group.subgroup + .row:nth-of-type(n) { background: blue; } 

Updated demo

+1
source

Source: https://habr.com/ru/post/1497307/


All Articles