CSS选择类中的非第一项[重复]

Posted

技术标签:

【中文标题】CSS选择类中的非第一项[重复]【英文标题】:CSS select non-first items in class [duplicate] 【发布时间】:2018-09-29 08:59:59 【问题描述】:

我有一些类跨度 (.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>

【问题讨论】:

【参考方案1】:

在第一个 .lines 上使用 :not 选择器

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

【讨论】:

【参考方案2】:

尝试颠倒您的逻辑,即为所有 .pre 跨度设置默认样式,然后使用 2 :first-child 选择器定位第一个 .pre,例如

.pre 
    background: red;


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

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

【讨论】:

也很好用。谢谢

以上是关于CSS选择类中的非第一项[重复]的主要内容,如果未能解决你的问题,请参考以下文章