CSS pseudo-class: nth-of-type ()

1

See ...

div .p:nth-of-type(2) {
  font-weight: bold;
}
DIV 1
<div div="div1">
  <p class="p">p1</p>
  <p>p2</p>
  <p>p3</p>
  <p class="p">p4</p>
</div>

DIV 2
<div id="div2">
  <p class="p">p1</p>
  <p>p2</p>
  <p>p3</p>
  <p class="p">p4</p>
</div>

In the example above, I want to select the second element of the parent (.p) class of a parent (div), and that is not the result. if I make use of nth-of-type(1 ) it works, which for me translated would be, select the first element of the parent type of a parent (div). But why nth-of-type(2) does not go there for the fourth paragraph of both divs, giving the bold effect ..

    
asked by anonymous 05.01.2015 / 19:38

2 answers

4

You can do this using combiners:

/*Seleciona a segunda ocorrência do elemento com a classe .p dentro de uma div */
div > .p ~ .p {
   font-weight: bold;
   color: blue;
}

/*Seleciona a terceira ocorrência do elemento com a classe .p dentro de uma div */
div > .p ~ .p ~ .p {
   font-weight: bold;
   color: green;
}
DIV1
<div div="div1">
  <p class="p">p1</p>
  <p>p2</p>
  <p>p3</p>
  <p class="p">p4</p>
</div>

DIV 2
<div id="div2">
  <p class="p">p1</p>
  <p>p2</p>
  <p>p3</p>
  <p class="p">p4</p>
  <p class="p">p5</p>
</div>

Each repetition of the class separated by the ~ combinator means a level in the class you want to choose.

Level 3 selectors: link

EDIT:

As I quoted in the comment while we did not have level 4 selectors the output would be to use JQuery: link

    
05.01.2015 / 20:45
0

If you want to select "children" just use "+":

Example

div p:first-child + p {
  font-weight: bold;
}
DIV 1
<div div="div1">
  <p class="p">p1</p>
  <p>p2</p>
  <p>p3</p>
  <p class="p">p4</p>
</div>

DIV 2
<div id="div2">
  <p class="p">p1</p>
  <p>p2</p>
  <p>p3</p>
  <p class="p">p4</p>
</div>

See I use the: first-child to refer to the first

and '+ p' to reference the next one, whenever you want a next, add '+ p'.

I can not say that this is the best way, but if I understand correctly, it works.

    
05.01.2015 / 20:01