CSS在课堂上选择非第一项

时间:2018-04-19 01:14:38

标签: css css-selectors

我有很多类(.pre)深度埋藏在其他一些跨度中。我正在尝试CSS选择除第一个之外的所有.pre。

我能找到的最好的答案是:CSS selector for first element with class 但仍无法使其发挥作用



.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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

使用第一个:not

上的.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>

答案 1 :(得分:1)

尝试反转你的逻辑,即为所有.pre跨度设置默认样式,然后使用2:first-child selectors定位第一个.pre,例如

.pre {
    background: red;
}

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

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