Select all odd elements, but nth-of-type (odd) does not help [closed]

2

I'm doing an exercise in which I have to color all the odd items in one color and the pairs in another.

As I have each article separated by section , I have implemented in CSS the following:

section:nth-of-type(odd){
   background: #DBDBDB;
}

section:nth-of-type(even){
   background: #33C9FF;
}

But the only one that works for me is the (even) coloring everything of the color specified in this one.

PS: Excuse me, before I put in two times, but it was because I was messing with him because of the error. I have corrected it several times and it still does not go.

Sorry for the delay I've been fiddling with the code and apparently, as I have already commented some I have had errors in the html. I feel the mess, and thanks for the contribution to all.

    
asked by Pavl 30.01.2018 в 21:17
source

2 answers

2

Try nth-child (even) and nth-child (odd) as follows:

section:nth-child(even) {background: #CCC}
section:nth-child(odd) {background: #FFF}
<section>  1 </section>
<section>  2 </section>
<section>  3 </section>
<section>  4 </section>

EDITED:

Testing the code with nth-of-type:

section:nth-of-type(odd){
   background: green;
}

section:nth-of-type(even){
   background: red;
}
<section>  1 </section>
<section>  2 </section>
<section>  3 </section>
<section>  4 </section>

Both tests if they work ... Maybe it's the way you're placing the HTML.

Greetings.

    
answered by 30.01.2018 / 21:21
source
0
  

The CSS pseudo-class: nth-of-type (an + b) selects, in the tree of the   document, the element that has an + b-1 brothers with the same name   of elements placed before him, for an n with positive value or   zero, and that has a parent element. See: nth-child for a   more detailed description of the syntax of the arguments of this   pseudo-class : nth-of-type (an + b) is a more flexible pseudo-selector and   useful if you want to make sure you select the same type of label,   no matter where it is located within your parent element, or that   other types of labels appear before her.

Developer Mozilla

Also:

  

The nth selector (n) matches every element that is the n-   that son, of a particular kind, of his father.

     

n can be a number, a keyword or a formula.

     

Tip: Look at the selector: nth-child () to select the   element that is the nth child, regardless of the type, of its   primary element.

section:nth-of-type(odd) {
    background: #444444;
    color: #fff;
}

section:nth-of-type(even) {
    background: #ffff00;
}
<body>

<section>Primera seccion.</section>
<section>Segunda seccion</section>
<section>Tercera seccion</section>
<section>Cuarta seccion</section>

</body>

PS: It may not work because you are using the selectors (HTML)

    
answered by 30.01.2018 в 21:26