Select every second element of a series of nested elements (each has only one child)

Viewed 145

Does a css selector exist that will target every second .letter?

Of course, I could have put all .letter elements on the same level and used :nth-child(2n), but they all depend on the position of the former letter, so I need the nestedness.

.firstname {
  position: relative;
  height: 40px;
  width: 40px;
  margin: 75px 0 0 75px;
  border: 1px solid red;
}
.letter {
  position: absolute;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  width: 40px;
  background: rgba(0,0,255,0.2);
}
.letter > div {
  transform: rotate(-40deg);
  top: 100%;
}
<div class="firstname">
  <div class="letter s">S
    <div class="letter e">E
        <div class="letter b">B
           <div class="letter a">A
             <div class="letter s2">S
               <div class="letter t">T
                 <div class="letter i">I
                   <div class="letter a2">A
                     <div class="letter n">N</div>
                   </div>
                 </div>
               </div>
             </div>
          </div>
        </div>
      </div>
    </div>
  </div>  
</div>

2 Answers

In case you want to play with only coloration here is a trick using filter where the idea is to use a 180deg hue-rotation to get back to the initial color after two iterations. This will simulate your selector.

It remains limited as solution because you will need to tweak the filter to have the coloration you want which is not a trivial task

.firstname {
  position: relative;
  height: 40px;
  width: 40px;
  margin: 75px 0 0 75px;
  border: 1px solid red;
}

.letter {
  position: absolute;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  width: 40px;
  background: rgba(0, 0, 255, 0.2);
  color:red;
  filter: hue-rotate(180deg) saturate(2);
}

.letter>div {
  transform: rotate(-40deg);
  top: 100%;
}
<div class="firstname">
  <div class="letter s">S
    <div class="letter e">E
      <div class="letter b">B
        <div class="letter a">A
          <div class="letter s2">S
            <div class="letter t">T
              <div class="letter i">I
                <div class="letter a2">A
                  <div class="letter n">N</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Unfortunately CSS doesn't have a single selector for grand children.

You'd need manually create a selector structure:

.firstname > .letter > .letter,
.firstname > .letter > .letter > .letter > lettter,
.firstname > .letter > .letter > .letter > lettter > .letter > lettter
{
/* style */
}
Related