1

I have a number spans of class (.pre) buried deep within a number of other spans. I am trying to CSS select all .pre except the first one.

The best I could find is this answer: CSS selector for first element with class but still was unable to make it work

.pre {
  background: blue;
}

.wrapper > .lines > .line > .pre ~ .pre {
  background: red;
}
<div class="wrapper">
  <span class="lines">
    <span class="line">
      <span class="pre">
        Pretext 1
      </span>
    </span>
  </span>

  <span class="lines">
    <span class="line">
      <span class="pre">
        Pretext 2
      </span>
    </span>
  </span>

  <span class="lines">
    <span class="line">
      <span class="pre">
        Pretext 3
      </span>
    </span>
  </span>
</div>
cycle4passion
  • 3,081
  • 3
  • 14
  • 28

2 Answers2

2

Use the :not selector on the first .lines

.pre {
  background: blue;
}

.wrapper .lines:not(:first-child) .pre {
  background: red;
}
<div class="wrapper">
  <span class="lines">
    <span class="line">
      <span class="pre">
        Pretext 1
      </span>
  </span>
  </span>

  <span class="lines">
    <span class="line">
      <span class="pre">
        Pretext 2
      </span>
  </span>
  </span>

  <span class="lines">
    <span class="line">
      <span class="pre">
        Pretext 3
      </span>
  </span>
  </span>
</div>
sol
  • 22,311
  • 6
  • 42
  • 59
1

Try inverting your logic, i.e. set a default style for all .pre spans, then target the first .pre using 2 :first-child selectors, e.g.

.pre {
    background: red;
}

.lines:first-child .line .pre {
    background: blue; 
}

https://codepen.io/anon/pen/NMPKKQ