Reputation: 105
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
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>
and this link will help you to understand better to know more about nth-child in css http://nthmaster.com/
Upvotes: 0
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:
li
element of the ul
ul
, which is the first element in body
a
in an li
element (styling of :nth-child(1)
wins)a
element that is not the first child of another element (styling of a
is used)span
elementem
inherits the text color of its parent (span
) which is the first child of a div
, so the styling of :nth-child(1)
is appliedAlso 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