CSS:向带有类的最后一个元素添加样式(不带JS) [英] Css: Add style to last element with class (without js)

查看:673
本文介绍了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>

这篇关于CSS:向带有类的最后一个元素添加样式(不带JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆