Css is odd and even on nested elements
https://jsfiddle.net/an5xvdvr/
I want to use css odd and even on 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 kind of magic rule that works for all cases.
source to share
div:nth-of-type
, select siblings, for example:
<div>sibling1</div>
<div>sibling2</div>
<div>sibling3</div>
<div>sibling4</div>
in your code all divs are the first chidrens, so they are all odd,
if I change your code and add <div>test2</div>
to your code, that's why <div>test2</div>
they <div>test</div>
are native:
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 cannot use nth-of-type, but you can use 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>
source to share
Mate, I don't think you can do this with a selector nth
because it is nested. I suggest you use the class and make it dynamic (php / js) if you don't know how deep the nest is and filter the class there.
Html
<div class="bg-black">
<div class="bg-white">
<div class="bg-black">
<div class="bg-white">
Test
</div>
</div>
</div>
</div>
CSS
div {
padding: 25px;
min-width: 100px;
min-height: 50px;
outline: 2px solid #333;
}
.bg-black {
background-color: black;
}
.bg-white {
background-color: white;
}
source to share
You can add some classes with jQuery:
Html
<div class="first-container">
<div>
<div>
<div>
Test
</div>
</div>
</div>
</div>
JQuery
CSS
source to share