Not counting the 1st div inside the parent div and using odd and even correctly

Viewed 39

I found something weird on using .someclass:nth-of-type(odd) or (even), no matter what I change it keeps counting from the first div (which is on the other class). Please see the example

.mktoFormCol{width:500px;}

.toggle-profile{width:100%;}

.mktoFormRow{
width: 40%;
display: inline-block;
padding: 1rem;
background-color: #7bd5f0a3;
}

fieldset.mktoFormCol .mktoFormRow:nth-of-type(odd) {
  background-color: #e60951a3;
}
<fieldset class="mktoFormCol">
  <div class="toggle-profile">should not count from this</div>
  <div class="mktoFormRow">1 left</div>
  <div class="mktoFormRow">2 right</div>
  <div class="mktoFormRow">3 left</div>
  <div class="mktoFormRow">4 right</div>
  <div class="mktoFormRow">5 left</div>
  <div class="mktoFormRow">6 right</div>
</fieldset>

<fieldset class="mktoFormCol">
  <div class="mktoFormRow">1 left</div>
  <div class="mktoFormRow">2 right</div>
  <div class="mktoFormRow">3 left</div>
  <div class="mktoFormRow">4 right</div>
  <div class="mktoFormRow">5 left</div>
  <div class="mktoFormRow">6 right</div>
</fieldset>

2 Answers

nth-of-type only works for tags

You can’t use it for classes or ids.

You’ll need to rework your html and css a little.

fieldset div:nth-of-type(odd) {
    ...
}

Then you’ll have to use a different tag for things you don’t want included.

<fieldset>
    <div>...</div>
    <div>...</div>
    <footer>I’m not affected by nth-of-type because I’m not a div</footer>
</fieldset>

I think that nth-of-type looks at the tag of the element, and will not pay attention to the class. If you change this to a <p> for instance, it works.

.mktoFormCol{width:500px;}

.toggle-profile{width:100%;}

.mktoFormRow{
width: 40%;
display: inline-block;
padding: 1rem;
background-color: #7bd5f0a3;
}

fieldset.mktoFormCol .mktoFormRow:nth-of-type(odd) {
  background-color: #e60951a3;
}
<fieldset class="mktoFormCol">
  <p class="toggle-profile">should not count from this</p>
  <div class="mktoFormRow">1 left</div>
  <div class="mktoFormRow">2 right</div>
  <div class="mktoFormRow">3 left</div>
  <div class="mktoFormRow">4 right</div>
  <div class="mktoFormRow">5 left</div>
  <div class="mktoFormRow">6 right</div>
</fieldset>

<fieldset class="mktoFormCol">
  <div class="mktoFormRow">1 left</div>
  <div class="mktoFormRow">2 right</div>
  <div class="mktoFormRow">3 left</div>
  <div class="mktoFormRow">4 right</div>
  <div class="mktoFormRow">5 left</div>
  <div class="mktoFormRow">6 right</div>
</fieldset>

Related