0

I need to select my number of items is odd. No matter an element class "box-media2"

Anyone has any idea/advice about this issue a part of adding a class "odd" ?

.box-media:nth-child(2n+1) {
  color: red;
}

.box-media2 {
  display: none;
}
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
Diego Sagredo
  • 149
  • 1
  • 11
  • nth-child() supports even and odd. `.box-media:nth-child(even)` or `.box-media:nth-child(odd)` – kfriend May 12 '17 at 20:35
  • Could you clarify: what's not working in the example you posted? – alexanderbird May 12 '17 at 20:40
  • @alexanderbird an example, red Test as odd and class "box-media2" display none. – Diego Sagredo May 12 '17 at 20:44
  • The whole question is a bit confusing. .box-media2 will NEVER be shown, because 1.) it has no content, thus no box will be rendered, and 2.) it's set to `display: none`. :nth-child() does not negate an element, just because it is hidden. – kfriend May 12 '17 at 20:44
  • Pseudo-classes, like `:nth-child`, select elements, not classes of elements. Using a class acts like a filter and makes the selection more restrictive. – j08691 May 12 '17 at 20:48
  • @kfriend .box-media2 will NEVER cannot? – Diego Sagredo May 12 '17 at 20:50

1 Answers1

1

you should use .box-media:nth-child(4n+1) to select odd .box-media children.

.box-media:nth-child(4n+1) {
  color: red;
}

.box-media2 {
  display: none;
}
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>
<div class="box-media">Test</div>
<div class="box-media2"></div>

That's because .box-media:nth-child(2n+1) searches for odd children (including .box-media and .box-media2), and applies styling to odd children that have a box-media class, which is always true in your case.

More about :nth-child selector on MDN.

Khaled Mashaly
  • 1,115
  • 9
  • 16