【问题标题】:CSS3 pseudo class not first and last childCSS3伪类不是第一个和最后一个孩子
【发布时间】:2013-05-25 17:01:29
【问题描述】:

我有一些以下 HTML 代码:

<ul>
    <li>number 1</li>
    <li>number 2</li>
    <li>number 3</li>
    <li>number 4</li>
    <li>number 5</li>
    <li>number 6</li>
    <li>number 7</li>
    <li>number 8</li>
    <li>number 9</li>
    <li>number 10</li>
</ul>

例如,我如何使用 CSS3 伪类使任何不是第一个或最后一个的 li 元素具有 background-colortomato?看来我可以使用:not 选择器。

【问题讨论】:

    标签: html css css-selectors pseudo-class


    【解决方案1】:

    这是一支笔 http://codepen.io/vendruscolo/pen/AeHtG

    你必须结合两个:not()伪类:

    li:not(:first-child):not(:last-child) {
      background: red;
    }
    

    这是MDN documentation:正如那里所说,它在 IE

    如果您需要 IE 8 支持,您必须依赖 Javascript 或使用其他类来指示哪个元素是最后一个子元素。事实上,IE 8(及更低版本)不支持 :last-child 伪类。

    【讨论】:

    • 是的。在IE不支持时非常有用
    【解决方案2】:

    两种方式:

    您可以设置一个通用规则,然后为 :first-child:last-child 项目覆盖它。这发挥了 CSS 的优势:

     li { background: red; }
     li:first-child, li:last-child { background: white; }
    

    或者,您可以使用:not 关键字结合两者:

    li { background: white; }
    li:not(:first-child):not(:last-child) { background: red; }
    

    在两者中,我个人更喜欢第一个 - 它更容易理解和维护(在我看来)。

    【讨论】:

    • 请注意,这在 IE8 上不起作用,因为 :last-child 不支持。
    【解决方案3】:

    这个适合我

    .candidate_verified_items ul li:not(:last-child),
    .candidate_verified_items ul li:first-child:not(:last-child) {
       border-right: 1px dashed #7b8db9;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2011-11-21
      • 1970-01-01
      • 2013-03-12
      • 2012-02-09
      • 1970-01-01
      相关资源
      最近更新 更多