【问题标题】::last-child OR :first-child NOT WORKING if followed by any element [duplicate]:last-child OR :first-child NOT WORKING 如果后跟任何元素 [重复]
【发布时间】:2022-01-06 15:50:52
【问题描述】:

我不知道为什么选择器 :first-child 适用于 'p' 元素和 NOT :last-child 并且对于以下 span 元素也会发生同样的情况 :last-child 有效,但 :first-child 无效。 (我想它们的默认父级是 body 元素)。我发现如果我在段落元素之后放置任何元素,它 (p:last-child) 不起作用,甚至对于以下元素 (span) 的行为也很奇怪,为什么当我 特别 时它不起作用> 告诉它选择父元素(在本例中为主体)的“p”(或跨度)元素的最后一个/第一个子元素?

<html>
<head>
<style> 
p:first-child  {
  background: red;
}
span:last-child  {
  background: red;
}
</style>
</head>
<body>

<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The second paragraph.</p>
<span>A..</span><span>B.. </span><span>C.. </span>

</body>
</html>

编辑:我刚刚找到所有这些 :first-of-type, last-of-type, first-child 和 :last-child 的 SPEC 说-“所选元素必须有一个父级。从第 4 级选择器开始,不再需要", 这意味着他们的规格有问题。如果他们不需要任何父母,那么它必须工作,即使他们需要,他们在我的情况下也有一个(身体元素)。首先,根据 SPEC,它们不再需要是子元素,其次,它们确实是默认 body 元素的子元素。因此,所有这些都应该起作用(相对于父体)。

【问题讨论】:

  • 它工作正常!您确定您的测试环境可以正常工作吗?
  • 我刚刚在w3schools编辑器里试了一下
  • :first-childlast-child 是必须单独匹配的条件。在它前面添加一个选择器,如pspan,只是进一步限制了已经匹配的元素列表。所以p:first-child 读作 Find all elements which are the first child elements of their parent;然后从找到的那些中,只给我p 元素

标签: html css


【解决方案1】:

因为第三个p 不是最后一个孩子,第一个span 不是父母的第一个孩子。

第三 pp:last-of-type,但不是 p:last-child
同样,firstspanspan:first-of-type,但不是 span:first-child

p:first-child  {
  color: red;
}
p:last-child {
  color: blue;  /*This doesn't work*/
}
p:last-of-type {
  color: green;
}
span:first-child  {
  color: red;  /*This doesn't work*/
}
span:first-of-type {
  color: blue;
}
span:last-child {
  color: green;
}
<div>
  <p>The first paragraph.</p>
  <p>The second paragraph.</p>
  <p>The second paragraph.</p>
  <span>A..</span>
  <span>B.. </span>
  <span>C.. </span>
</div>

【讨论】:

  • 谢谢,但你能解释一下,为什么?如果 first-child 有效,则表示其父级(body 元素)的第一个子级,就像最后一个子级 shud 是父级(body 元素)的最后一个 p 一样。据我了解,这些孩子是相对于父 body 元素的。因此,父体的最后一个 p 元素是最后一个 p 元素,为什么不是呢?你能解释一下吗?至少 SPEC 是这么说的。但是,如果我给这些 p 另一个特定的父级(例如 div ),那么同样有效。 SPEC 说它应该适用于任何父母的任何孩子。在我的例子中,父元素是 Body 元素。
  • 我刚刚发现所有 :first-of-type、last-of-type、:first-child 和 :last-child 的 SPEC 都说——“所选元素必须有父元素。从选择器级别 4 开始,不再需要这样做”,这意味着他们的规范中存在故障。如果他们不需要任何父母,那么它必须工作,即使他们需要,他们在我的情况下也有一个(身体元素)。你在什么意义上说,“第三个 p 不是最后一个孩子,第一个跨度不是父母的第一个孩子。”。首先,根据 SPEC,它们不再需要是子元素,其次,它们确实是 body 元素的子元素。
【解决方案2】:

您无法理解这些选择器是如何工作的,并且确实有效。

:first-child:last-child 是必须自行匹配的条件。在它前面加上pspan 之类的选择器只是进一步限制了已经被:first-child:last-child 匹配的元素列表

所以p:first-child实际上的意思是找到所有元素的第一个子元素;然后从找到的那些中,只给我p 元素

【讨论】:

  • 非常感谢....
猜你喜欢
  • 2016-06-24
  • 2013-03-03
  • 2014-10-16
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2011-12-17
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多