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.

+3


source to share


4 answers


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>
      

Run codeHide result


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>
      

Run codeHide result


+1


source


I don't think you can do this with CSS nth

. This does not work on a nested element, but only on elements within the same parent. I did this, this is a bit of a workaround, but it works.



Updated JsFiddle

+1


source


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.

Fiddle

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;
}

      

+1


source


You can add some classes with jQuery:

Html

<div class="first-container">
  <div>
    <div>
      <div>
      Test
      </div>
    </div>
  </div>
</div>
      

Run codeHide result


JQuery

$( ".first-container div" ).filter( ":even" ).addClass( "odd" );
      

Run codeHide result


CSS

.odd {
    background: #eee;
}
      

Run codeHide result


0


source







All Articles