CSS第一个孩子在Div元素中的奇怪行为

时间:2017-04-18 10:35:22

标签: html css

所以这是我的代码:

.tagBoxContent p:first-child {
  color: blue;
}

.tagBoxContent p:last-child {
  color: red;
}
<div class="tagBoxContent">
  <a class="tagHeadline">with <span>'chat'</span> tagged articles</a>
  <p>Lorem ipsum dolor sit amet,</p>
  <p>Integer ma</p>
</div>

为什么first-child不会触发p标签但是最后一个子元素呢?如何在没有第一个孩子或有工作的第一个孩子的情况下调用第一个p标签?我研究了很多,但没有找到任何重复相同的问题。

2 个答案:

答案 0 :(得分:9)

您正在使用:first-child并且它不是第一个孩子。相反,请使用:first-of-type

.tagBoxContent p:first-of-type {
  color: blue;
}

.tagBoxContent p:last-child {
  color: red;
}
<div class="tagBoxContent">
  <a class="tagHeadline">with <span>'chat'</span> tagged articles</a>
  <p>Lorem ipsum dolor sit amet,</p>
  <p>Integer ma</p>
</div>

答案 1 :(得分:0)

使用nth-child()选择不是第一个或最后一个孩子的孩子

.tagBoxContent p:nth-child(2) {
  color: blue;
}

.tagBoxContent p:last-child {
  color: red;
}
<div class="tagBoxContent">
  <a class="tagHeadline">with <span>'chat'</span> tagged articles</a>
  <p>Lorem ipsum dolor sit amet,</p>
  <p>Integer ma</p>
</div>