1

I like to perform a selection of the first and last element which does not contain the class hidden.

   <div class="gallery-cell hidden"></div>
    <div class="gallery-cell hidden"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell"></div>
    <div class="gallery-cell hidden"></div>
    <div class="gallery-cell hidden"></div>    

This works for me to catch all elements.

But how do I get only the first and last?

.gallery-cell:not(.hidden){
    opacity:0.2 !important;
}

Pure css would be awesome.

Alexander Hein
  • 960
  • 3
  • 19
  • 44

2 Answers2

3

This is unfortunately not possible in CSS only, because first-child, last-child, and nth-of-type all don't accomplish quite what we're looking for. Following is a JavaScript solution.

Live Demo:

var notHidden = document.querySelectorAll(".gallery-cell:not(.hidden)");
notHidden[0].classList.add("targeted");
notHidden[notHidden.length - 1].classList.add("targeted");
.gallery-cell {
    width: 100px;
    height: 100px;
    background-color: black;
    margin: 10px;
}

.targeted {
    opacity:0.2 !important;
}
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
0

You can catch the first one using the adjacent sibling selector (+) with a :not() pseudo-class selector like this: .gallery-cell.hidden+:not(.hidden). I don't have a solution for "last-before..."

.gallery-cell {
  background-color: lightblue;
  height: 20px;
  border: 1px black solid;
}
.hidden {
  background-color: blue;
}

.gallery-cell.hidden+:not(.hidden){ /* <- This will catch first non-hidden */
  border: 2px green solid;
}
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell"></div>
<div class="gallery-cell hidden"></div>
<div class="gallery-cell hidden"></div>
Amit
  • 45,440
  • 9
  • 78
  • 110