Behaviour of the pseudo-class :Nth-Child

Asked

Viewed 257 times

5

Unfortunately the question marked as "possible duplicate" (and its responses) address something else, specifically the functioning of variable n in formulas passed in the :nth-child(), which neither contemplates nor answers to the doubts set out in this question.

I did some research and saw that the pseudo-class :nth-child() does not work when used with classes. For example:

.classe:nth-child(1){
   color: red;
}
<div>texto preto</div>
<div class="classe">este texto era pra ser vermelho :(</div>
<div class="classe">texto preto</div>

The text of the first element of the class .classe does not turn red, as expected. However, if I change the value of .nth-child for (2), will apply the red color to the first element of the class (not to the second, as expected):

.classe:nth-child(2){
   color: red;
}
<div>texto preto</div>
<div class="classe">este texto é vermelho, mas não deveria :/</div>
<div class="classe">este texto era pra ser vermelho :(</div>

Well, if the .nth-child() does not work with classes, because when I change the value to (2) the property is applied to the wrong element, and with the value (1) nothing happens?

And when I remove the class from the second div, Unlike the previous example, nothing happens:

.classe:nth-child(2){
   color: red;
}
<div>texto preto</div>
<div>texto preto</div>
<div class="classe">texto preto</div>

In the example above, if I change the value of (1) for (3), will change the color of the last div, the one with the class .classe. But if I remove the class from the div, nothing will happen.

I mean, the class is making some influence, I just couldn’t understand what that influence would be.

The question is: the style .classe:nth-child() should not be ignored by the CSS? What is the criterion that the CSS uses in these cases, since in the second example the color was changed (even in the unwanted element)?

  • 2
  • the N specifically explains why it does not work based on classes, will understand the basis of the child/sibling elements and that the selector’s behavior is based on this, the other question that complements the explanation is probably this https://answall.com/q/290866/3635, where I explain in the answer clearly, direct sibling elements, or is independent of any other characteristic, the consideration is for the direct, then even with the class selector, the Nth-CHILD will evaluate all children.

  • It is basically what the Ugo answered a group of sibling elements, ie will evaluate to all siblings in the N-enisimo

  • 1

    @Before formulating the question I read all these topics, but for me they have not yet been able to clarify the doubts I had. Hugocss' response was very specific and clear to me. I believe it can help someone as layman as I am in the future. Thanks!

  • I do not see so extra complement in the answer, both links that I mentioned completely address, here the error falls more to typo/usage error, sorry I’m just being honest about the technical approach, if you understand the technical functioning understands the problem, regardless of having examples or not, the idea is to understand the word CHILD, of course CSS is confusing at first glance, but if the technical understanding is explored there your perception changes from angle which will make better understand the behavior of DOM, box-model and other selectors in general ;)

  • @Guilhermenascimento It’s easier for you to understand. I’m still learning some things. But I appreciate the explanations.

  • But that’s what I’m explaining, if you try to understand technical behavior you’ll understand why something fails, of course there are situations called "computing" that even having technical knowledge still sometimes we do not understand why something stops working or back to work alone (something common to anyone who works in the area of IT), but still you should not abandon or run away from technical knowledge, understanding this is the key to mastering things, unlike this is like wanting to drive a car even before learning to ride ;)

  • I hope you understand all the technical explanation and what I am trying to give you so that you avoid the path of stones in the future, after all for most of the things there are reasons (technical reasons) to behave in certain ways, happy new year!

  • @Guilhermenascimento Thanks! to you too!

Show 4 more comments

2 answers

5


The CSS rule has to be valid to be applied, meaning there have to be two things to be true, class and son.

And see that the nth-child is for a group of fraternal elements, It doesn’t matter without class or not. The class is only a complement to the rule, because as you can see it is possible to select an element in the group only with :nth-child(n) without declaring class the type of element.

The pseudo-class CSS :nth-child() selects elements based on their positions in a group of sibling elements.

Source in the Mozilla documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/:Nth-Child

Let’s take a look at the example.

Here we have a group of 5 brothers, all of them are :nth-child(1)a(5), but for the CSS to be applied it has to be the :nth-child(X) and have the class .classe, then it has to be under both conditions true. I left the comments in the code

/* vai aplicar */
.classe :nth-child(1){
  color: green;
}
/* não vai aplicar, não tem a classe */
.classe:nth-child(1){
  color: red;
}
/* vai aplicar tem a classe e é o 2 irmão */
.classe:nth-child(2){
  color: red;
}
/* não vai aplicar, pois é o 4 filho, mas sem a classe */
.classe:nth-child(4){
  color: red;
}
/* vai aplicar */
.classe:nth-child(5){
  color: blue;
}
<div>

  <div class="">irmão 1 - este texto a regra falha</div>
  <div class="classe">irmão 2 -texto deve ser vermelho</div>
  <div class="classe">irmão 3
    <div>filho 1 selecionado apenas com ":nth-child(1)" sem classe ou elemento</div>
    <div>filho 2</div>
  </div>
  <div class="">irmão 4 - este texto a regra falha</div>
  <div class="classe">irmão 5 - este texto é azul :(</div>

</div>

  • Now I understood the stop... I thought it was kind of complicated but I see that it is very simple. Both conditions must meet the selector. : D

  • I was about to formulate such a response!

  • 1

    @Sam I assume that when I saw your examples I was very confused also rss, but then I looked and the code kept looking at me back, then it came to shit! But it was an interesting question on your part.

  • @Lipespry beat me to that :D

  • 1

    For you to see that a simple explanation clears everything, and what seemed complicated becomes simple. But I swear, I got a little messed up with it, I wasn’t getting the logic. Thanks!

  • It is worth remembering, also, that it is independent of the type of the elements. nth-child() will get all child elements. Be they div, p, span, etc.!

  • @Lipespry what confused me at first was this word "son"... when in fact he selects the brothers, who at the root would be sons of the body, or if within a div for example would be sons of this div, but brothers among themselves. This sometimes confuses a little who is not familiar

  • Dude, I’ll even formulate an answer in addition to yours. Go that glue...

  • @Lipespry yes be the will, it is always good to complement, because it is as a base date, even if it is not totally within the scope of the issue, it is worth as an extra point rss

  • @Sam when we see all the elements, regardless of class, as members of the same group then Nth-Child starts to make sense. Happy New Year! ;) [] s

  • for you too!

Show 6 more comments

3

The selector nth-child(n) corresponds to each element that is the umpteenth son, regardless of the type, of his father.

Source: W3schools - CSS :Nth-Child() Selector

When using such selector, you should pay particular attention to the parent element.

Hard to understand, but so it is! You create the selector and it considers all elements of his father’s children! (Bugou?!)

"- The text of the first element of the class .classe does not turn red, as expected. However, if I change the value of .nth-child for (2), will apply the red color to the first element of the class (not to the second, as expected)." (sic)

See this example (in the question):

.classe:nth-child(1) {
   color: red;
}
<!DOCTYPE html>
<html>
    <body>
        <div>texto preto</div>
        <div class="classe">este texto era pra ser vermelho :(</div>
        <div class="classe">texto preto</div>
    </body>
</html>

  • <body> is the parent element;
  • <div>texto preto</div> is the child element #1. Equivalent to :nth-child(1);
  • <div class="classe">este texto era pra ser vermelho :(</div> is the child element #2. Equivalent to :nth-child(2);
  • <div class="classe">texto preto</div> is the child element #3. Equivalent to :nth-child(3);

Turns out for the dial .classe:nth-child(1) working on son #1, he could not have mentioned the target class: .classe! That way, it just goes "bindar" when hitting the element number with the class (Ahh, and don’t forget Dad!).

Another issue: if consider the children of the father, regardless of the type of son! Behold:

<body>
    <div>texto preto</div>
    <p class="classe">este texto era pra ser vermelho :(</p>
    <span class="classe">texto preto</span>
    <strong>texto preto</strong>
    <i>texto preto</i>
</body>

  • <body> is the parent element;

  • <div>texto preto</div> is the child element #1;

  • <p class="classe">este texto era pra ser vermelho :(</p> is the child element #2;

  • <span class="classe">texto preto</span> is the child element #3;

  • <strong>texto preto</strong> is the child element #4;

  • <i>texto preto</i> is the child element #5;

This answer is a complement of reply of hugocsl.

  • 2

    Good explanation. Obg!

  • That’s it right there. I give you a hint, put the example you did in Snippet, so we can run and see the example working, it helps a lot to view and "link" the output with the code text.

  • 1

    @hugocsl your tip is an order! (I find snippet unnecessary when the goal is not to run the code, but your opinion is worth!)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.