为什么最后一个 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
属性仅适用于作为其父容器的最后一个子元素的元素。在你的情况下,span
是 last-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
相反,它会起作用,因为第四个 p
是 last-of-type
p
.
关于html - 最后一个 child 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26589814/