首页 > 解决方案 > 选择每个

不是其父元素的第一个子元素的元素

问题描述

如果我想选择<p>不是其父元素的第一个元素的每个元素,那么正确的 CSS 选择器是什么?

就像下面的这个片段,只是反转!(所以“第二”、“第三”、“第四”是红色的,“第一”是正常的)

p:first-of-type {
  background: red;
}
<body>
  <p>The first paragraph.</p>
  <p>The second paragraph.</p>
  <p>The third paragraph.</p>
  <p>The fourth paragraph.</p>
</body>

标签: htmlcsscss-selectors

解决方案


您可以使用:not否定伪类。请注意,在组合伪类时,您必须将第二个伪类放在括号内:not(:first-of-type)

p:not(:first-of-type) {
  background: red;
}
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

请注意,如果您特别希望选择元素的第一个子元素以外的所有元素,则可以使用:not(:first-child). 请注意,在这种情况下,选择器位于元素上,而不是父元素:

.parent p:not(:first-child) {
  background: red;
}
<div class="parent">
  <p>The first paragraph.</p>
  <p>The second paragraph.</p>
  <p>The third paragraph.</p>
  <p>The fourth paragraph.</p>
</div>


推荐阅读