CSS-选择器nth-child

时间:2018-11-20 15:15:50

标签: html css

为什么所有元素都被染成红色?

<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;
}

我认为元素应该适当地着色。 spanph1是元素div的子代?

1 个答案:

答案 0 :(得分:4)

.parent:nth-child(1)的意思是“该元素是其父元素的第一个子元素,并且是parent类的成员的”。

它与spanph1不匹配,因为它们没有class="parent"

继承人从其父级继承了红色,而 拥有该类,并且父级中的第一个子级。

您在那里需要一个孩子或后代combinator

.parent > :nth-child(1)
.parent :nth-child(1)
相关问题