Problem with nth-child

7

I have the following scenario:

HTML:

<div class='linha visivel'>Visivel</div>
<div class='linha visivel'>Visivel</div>
<div class='linha oculto' style='display:none'>Invisivel</div>
<div class='linha visivel'>Visivel</div>

CSS:

.visivel:nth-child(odd) { background: yellow }
.visivel:nth-child(even) { background: green }

Results found:

  • 1stlinewithvisibleclassYELLOW
  • 2ndlinewithvisibleclassGREEN
  • 3rdlinewithvisibleclassGREEN

Expectedresult:

  • 1st line with visible class YELLOW
  • 2nd line with visible class GREEN
  • 3rd line with visible class YELLOW

link

From what I understand, nth-child should alternately paint the divs with the visible class. But as there is a hidden div in the middle it does not do it properly.

Am I wrong about behavior? How to correct?

    
asked by anonymous 27.02.2015 / 18:40

2 answers

3

Based on the comments and the OS response in English, I had no other solution than to use jQuery:

 $(".visivel:even").css("background-color", "green");
 $(".visivel:odd").css("background-color", "yellow");

@utluiz comment on "unexpected" behavior:

  

The behavior is this, since the selector works on the basis of the nodes   of the DOM and does not apply only to what is selected by CSS.

    
27.02.2015 / 19:02
1

On the operation of nth-child(odd) and nth-child(even) : When you put even and odd it will color the even and odd lines, respectively.

Another way to do it, without using jQuery, is to create a div and put all elements inside it (according to this answer ):

.todas {
  line-height: 1.2em;  
  background-color: yellow; 
  background-image: linear-gradient(transparent 50%, green 50%);
  background-size: 100% 2.4em;
}
<div class="todas">
  <div class='linha visivel'>Visivel</div>
  <div class='linha visivel'>Visivel</div>
  <div class='linha oculto' style='display:none'>Invisivel</div>
  <div class='linha visivel'>Visivel</div>
</div>
    
02.02.2017 / 20:53