https://jsfiddle.net/an5xvdvr/
I want to use css odd and even on a nested html structure.
The first background color should be white, the next black, the next white, the next black and so on until it reaches Test
.
html
<div>
<div>
<div>
<div>
Test
</div>
</div>
</div>
</div>
css
div {
padding: 25px;
background: #eee;
min-width: 100px;
min-height: 50px;
outline: 2px solid #333;
}
what I tried
I tried this without success:
div:nth-of-type(even) {
background: #eee;
}
The depth can be unlimited so I need some magic rule that works for all cases.
div:nth-of-type
selector,select siblings, for example :
<div>sibling1</div>
<div>sibling2</div>
<div>sibling3</div>
<div>sibling4</div>
in your code all divs are first chidren,so all of them are odd,
if i change your code and add <div>test2</div>
to your code ,so <div>test2</div>
and <div>test</div>
are sibling :
div {
padding: 25px;
background-color: #fff;
min-width: 100px;
min-height: 50px;
outline: 2px solid #333;
}
div:nth-of-type(even){
background-color: red;
}
<div>
<div>
<div>
<div>
Test
</div>
<div>
test2
</div>
</div>
</div>
</div>
so in your case ,you can not use nth-of-type but can use of class selector :
div {
padding: 25px;
background-color: #eee;
min-width: 100px;
min-height: 50px;
outline: 2px solid #333;
}
.even {
background-color:#fff;
}
<div class="even">
<div>
<div class="even">
<div>
Test
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With