paige
paige

Reputation: 105

css nth-child(1) chose the second element, why?

What I want: To understand nth-child(n). My understanding is that the nth- child(1) will choose every first element. So apple, fruit, banana should be chosen to display red.

What actually shows: But tomato and mango were also chosen and displayed red.

Code:

a {
    text-decoration: none;
    color: black;
}

:nth-child(1) {
    color: red;
}
<ul>
    <li>apple</li>
    <li>tomato</li>
    <li>
        <a href="#">fruit</a>
        <a href="#">juice</a>
    </li>
</ul>
<div>
    <span>
        <a href="#">banana</a>
        <em>mango</em>
    </span>
</div>

Upvotes: 2

Views: 1391

Answers (2)

Prakash S
Prakash S

Reputation: 132

Mr.Arjan answer is perfect. In addition to that I have changed your code for your better understanding.

    <ul>
    <li>apple</li>
    <li>tomato</li>
    <li>
        <a href="#">fruit</a>
        <a href="#">juice</a>
    </li>
</ul>
<div>
    <span>
        <a href="#">banana</a>
        <em>mango</em>
    </span>
</div>

Working Fiddle here

and this link will help you to understand better to know more about nth-child in css http://nthmaster.com/

Upvotes: 0

Arjan
Arjan

Reputation: 9874

First, :nth-child(1) also includes html:nth-child(1), which means all text will be red. Also note that ul is the first child of body. (html and body elements are added when you run the snippet.)

The reason almost all text is red is somewhat complicated:

  • apple: red because it is text in the first li element of the ul
  • tomato: red because it inherits the color of ul, which is the first element in body
  • fruit: red because it is the text of the first a in an li element (styling of :nth-child(1) wins)
  • juice: black because it is the text of an a element that is not the first child of another element (styling of a is used)
  • banana: red because it is the text of the first child of a span element
  • mango: red because em inherits the text color of its parent (span) which is the first child of a div, so the styling of :nth-child(1) is applied

Also note that any text in the div will be red, because the div inherits the color from html (which is a first child). You may want to specify an explicit text color for html which can be used instead.

Upvotes: 5

Related Questions