为什么所有元素都被染成红色?
<div class="parent">
<span>1</span>
<p>2</p>
<h1>3</h1>
</div>
.parent:nth-child(1) {
color: red;
}
.parent:nth-child(2) {
color: green;
}
.parent:nth-child(3) {
color: blue;
}
我认为元素应该适当地着色。 span
,p
,h1
是元素div
的子代?
答案 0 :(得分:4)
.parent:nth-child(1)
的意思是“该元素是其父元素的第一个子元素,并且是parent
类的成员的”。
它与span
,p
或h1
不匹配,因为它们没有class="parent"
。
继承人从其父级继承了红色,而 拥有该类,并且是父级中的第一个子级。
您在那里需要一个孩子或后代combinator:
.parent > :nth-child(1)
.parent :nth-child(1)