情景:有时候想要这样一种效果,
当列表中有一个元素时,显示一个元素并且充满整一行;
当列表中有两个元素时,显示两个元素并且平分宽度;
当列表中有三个元素时,三等分宽度;
当列表中有四个元素时,四等分宽度;
…
实现:利用css的选择器实现。
html
<ul class="list">
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
<li class="item">
</li>
</ul>
css
//一个元素:
//要求元素既是第一个元素,也是最后一个元素
.item:first-child:last-child {}
//两个元素
//要求元素是第一个元素,也是倒数第二个元素
//~表示选择当前元素的兄弟元素
.item:first-child:nth-last-child(2),
.item:first-child:nth-last-child(2)~.item{}
//三个元素
//要求元素是第一个元素,也是倒数第三个元素
.item:first-child:nth-last-child(3),
.item:first-child:nth-last-child(3)~.item{}
//四个元素
//要求元素是第一个元素,也是倒数第四个元素
.item:first-child:nth-last-child(4),
.item:first-child:nth-last-child(4)~.item{}