用某个选择器过滤出来一个元素集合,当我们想选中最后一个元素的时候,是不是很容易想到:last-child?比如,有下面一段CSS和HTML片段:
<style> .section{ margin-bottom: 50px; } .section1-item:last-child{ color: blue; }</style>
<section class="section section1"> <header>header</header> <p class="section1-item card">111</p> <p class="section1-item card">222</p> <p class="section1-item card">333</p> <p class="section1-item card">444</p> <footer>footer</footer></section>
本来是想选中<p class="section1-item card">444</p>
给它设置颜色为蓝色的,结果什么也没有发生。为什么?
查看W3C的相关介绍:
The :last-child pseudo-class represents an element that is the last child of some other element.
someselecttor:last-chid 所表示的是,如果someselecttor所选中的某个节点恰好是其父元素的最后一个直接子节点,那么该选择器生效。而不是表示someselecttor选中的节点集合的最后一个。
同理,我们马上可以想到,:first-child是不是也有类似问题?添加一句样式.section1-item:last-child{ color: red; }
到上面的例子中一试就知道,问题果然存在。
someselecttor:first-chid 所表示的是如果someselecttor所选中的某个节点恰好是其父元素的第一个直接子节点,那么该选择器生效。