Css: Add style to last element with class (without

2019-07-25 06:01发布

问题:

This question already has an answer here:

  • Can I combine :nth-child() or :nth-of-type() with an arbitrary selector? 5 answers

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>