上一篇中曾提到,someselecttor:last-chid 所表示的并不是someselecttor选中的节点集合的最后一个。那么,怎么达到这个效果呢?对,可以用:last-of-type。来个例子试试看吧!
<style> .section{ margin-bottom: 50px; } .section1-item:last-of-type{ color: green; } </style> <section class="section section1"> <header>header</header> <p class="section1-item">111</p> <p class="section1-item">222</p> <p class="section1-item">333</p> <p class="section1-item">444</p> <footer>footer</footer> </section>果然,把<p class="section1-item">444</p>给加上了绿色。不过,当我们把上面代码片段中的<footer>footer</footer>也加上 class="section1-item",问题来了,居然给<p class="section1-item">444</p>和<footer class="section1-item">footer</footer>所标示的两个元素都给加上了绿色!
我们继续把上面的HTML代码片段进行修改,改成:
<section class="section section1"> <header>header</header> <p class="section1-item">111</p> <p class="section1-item">222</p> <p class="section1-item">333</p> <footer class="section1-item">444</footer> <footer class="section1-item">footer</footer> </section>即只是把<p class="section1-item">444</p>改成了<footer class="section1-item">444</footer>,而CSS样式不作修改。当再次预览效果的时候,发现被加上绿色的元素分别是<p class="section1-item">333</p>和<footer class="section1-item">footer</footer>。这下答案就很明显了:
someselector:last-of-type不仅与someselector这个选择器相关,还与符合该选择器的元素的标签相关。
再看一下W3C的说明:
The :last-of-type pseudo-class represents an element that is the last sibling of its type in the list of children of its parent element.
这里所谓 the last sibling of its type其实讲得并不是很清楚,但仔细琢磨,这里的type的意思应该就是不仅仅与选择器相关,还与标签相关。
这时,你可能已经想到了,:first-of-type肯定也有类似的问题。的确,如你所料。
有了这一篇和上一篇的经验,遇到那不太准的CSS选择器,先进行如下处理:
1、翻一下W3C的说明
2、试验一下
相关资源:七夕情人节表白HTML源码(两款)