Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select first and last visible items in a list

Given a container with div children, some of which might have a .hidden class, how can I select the first and last visible items (that don’t have that class), using only css?

I tried:

div:not(.hidden):last-child Which doesn’t work because last-child is always the last child.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I mean in 2 declarations, not both at the same time.

>Solution :

Try the :nth-child() / :nth-last-child() pseudo-classes. Note that support is a little spotty, especially on mobile

.hidden {
  opacity: .2;
}

li:nth-child(1 of :not(.hidden)),
li:nth-last-child(1 of :not(.hidden)) {
  color: red;
}
<ul>
  <li class="hidden">One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li class="hidden">Five</li>
</ul>
  

Further reading:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading