【问题标题】:CSS select non-first items in class [duplicate]CSS选择类中的非第一项[重复]
【发布时间】: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>

【问题讨论】:

    标签: css css-selectors


    【解决方案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

      【讨论】:

      • 也很好用。谢谢
      猜你喜欢
      • 2018-03-16
      • 2018-01-07
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 2021-05-27
      • 2015-02-02
      • 2022-01-07
      • 2022-01-13
      相关资源
      最近更新 更多