html - 最后一个 child 的行为

标签 html css css-selectors

为什么最后一个 p 没有突出显示?

w3schools 说:

Specify a background color for the p element that is the last child of its parent

所以最后一个 p 应该突出显示吧?

<style> 
div p:last-child {
    background: #ff0000;
}
</style>

<div>
  <p>The first paragraph.</p>
  <p>The second paragraph.</p>
  <p>The third paragraph.</p>
  <p>The fourth paragraph.</p>
  <span>The first span.</span>
<div>

对于你来说,使用这个 - 这不是我的问题:

div p:last-of-type {...}

最佳答案

Last-child 没有选择您期望它选择的内容(您需要 last-of-type )。 last-child属性仅适用于作为其父容器的最后一个子元素的元素。在你的情况下,spanlast-child :

<div>
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>
    <span>The first span.</span> <!-- this <span> is the "last-child" -->
<div>

所以 CSS 选择器 p:last-child {}没有任何东西可供选择,因为它正在寻找容器的最后一个子容器也是一个 <p> 元素。这是一个更具体、真实的类比:

您有三个 child :

  • jack ,17 岁
  • 苏珊,14 岁
  • Alex,10 岁

在标记中,这看起来像:

<mother>
    <jack>17</jack>
    <susan>14</susan>
    <alex>10</alex>
</mother>

空白:last-child {}选择器将选择亚历克斯,因为他是您的最后一个 child 。但是,您正试图选择某种类型的最后一个 child ,在这种情况下我们会说他们的 name是类型。 Susan:last-child ,那么,将不起作用,因为即使 Susan 是您的 child 中最后一个被命名为 Susan(例如,具有类型 name 的“Susan”),她不是 em> 你生的最后一个 child 。

如果您使用 last-of-type相反,它会起作用,因为第四个 plast-of-type p .

关于html - 最后一个 child 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589814/

相关文章:

javascript - CSS3 列的第 n 个子元素

html - 如何使用 nth-child 对带有 rowspan 的表进行样式设置?

html - 无法为导航菜单设置背景颜色

javascript - 重叠下拉菜单

javascript - JS 和 CSS 文件未在 html 中加载

html - 使用 css content 属性渲染内容

html - div 始终从父级获取行高

css - 当检查输入时,如何将 css 应用到父级的同级元素?

javascript - 将鼠标悬停在一个元素上以将类添加到另一个元素?

javascript - 正确缩放 html 并使用 javascript/jquery 附加新信息