Css: Add style to last element with class (without js) [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-24 17:37:45

问题


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>

Need to select last post with pinned class (i.e. 2).

fiddle


回答1:


Problem:

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.

Alternative:

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>


来源:https://stackoverflow.com/questions/36446517/css-add-style-to-last-element-with-class-without-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!