CSS:向带有类的最后一个元素添加样式(不带JS)
问题描述:
我在创建css(sass)选择器时遇到问题,该选择器选择列表中具有类的最后一个元素(没有JAVASCRIPT ):
I have a problem with create css (sass) selector, which select last element with class in list (WITHOUT JAVASCRIPT):
<ul>
<li class="post pinned">1</li>
<li class="post pinned">2</li>
<li class="post">3</li>
<li class="post">4</li>
</ul>
需要选择固定类别(即2)的最后一个帖子.
Need to select last post with pinned class (i.e. 2).
答
问题:
实际上:last-child
不起作用,因为它不管容器有什么类都只会选择容器的最后一个子元素,而last-of-type
却不起作用,因为它只能从容器中选择具有特定类型的最后一个元素容器.
In fact :last-child
don't work because it only selects the last child of the container no matter what class it has, and last-of-type
don't work because it only selects the last element with a specific type from your container.
替代:
因此,基本上最好的解决方案是对此类元素使用专用的类:
So basically the best solution is to use a dedicated class for such element:
.micropost {} .micropost.pinned {
color: red;
}
.micropost:last-child {
color: green;
}
.lastPinned {
background-color: green;
}
<ul>
<li class="micropost pinned">1</li>
<li class="micropost pinned lastPinned">2</li>
<li class="micropost">3</li>
<li class="micropost">4</li>
<li class="micropost">5</li>
<li class="micropost">6</li>
<li class="micropost">7</li>
</ul>