代码之家  ›  专栏  ›  技术社区  ›  StefanBob

CSS选择器将before伪元素添加到除first和last之外的所有框中?[副本]

  •  3
  • StefanBob  · 技术社区  · 8 年前

    如何让CSS选择器将before伪元素添加到除第一个和最后一个之外的所有框中?箱号是动态的。

    .box:not(:first-of-type):before, .box:not(:last-of-type):before {
        ...
    }
    

    上面的其中一个有效,但是当我将它们组合在一起时,或者即使我将它们分开并复制CSS,它也不起作用,即在所有元素之前添加。

    .box-container {
    width: 100%;
      display: flex;
      justify-content: space-around;
    }
    
    .box {
      display: block;
      width: 100px;
      height: 100px;
      position: relative;
      background-color: blue;
    }
    
    .box:not(:first-of-type):before,
    .box:not(:last-of-type):before {
      content: '';
      display: block;
      width: 2px;
      height: 100px;
      position: absolute;
      left: -20px;
      background-color: red;
    }
    <div class="box-container">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>

    我的第一个想法是给他们所有的伪元素,但是 display: none; 对于类型的第一个和最后一个。

    只是想知道这种类型的选择器在CSS中是否可以使用上面这样的一行

    2 回复  |  直到 8 年前
        1
  •  4
  •   Temani Afif    8 年前

    只是因为当它不是 first-of-type 它可以是一个 last-of-type ,因此,如果不使用第一个规则选择它,则使用第二个规则,反之亦然。您的两个规则组合起来只相当于 .box::before

    你可以试试这个,把它们组合在一个选择器中,这样它就不是一个 第一种类型 和 不是一个 类型的最后一个 :

    .box-container {
    width: 100%;
      display: flex;
      justify-content: space-around;
    }
    
    .box {
      display: block;
      width: 100px;
      height: 100px;
      position: relative;
      background-color: blue;
    }
    
    .box:not(:first-of-type):not(:last-of-type)::before {
      content: '';
      display: block;
      width: 2px;
      height: 100px;
      position: absolute;
      left: -20px;
      background-color: red;
    }
    <div class="box-container">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
        2
  •  1
  •   ark__n    8 年前

    因为同样的原因 answer , 不是 其中一个伪类将选择另一个。你必须将它们嵌套以产生“和”效果。

    另一个版本,不使用 不是 使用的伪选择器 第n个孩子 以及 最后一个孩子 . 正如您在问题中所说,它们都支持动态计数。

    .box-container {
    width: 100%;
      display: flex;
      justify-content: space-around;
    }
    
    .box {
      display: block;
      width: 100px;
      height: 100px;
      position: relative;
      background-color: blue;
    }
    
    .box:nth-child(n+2):nth-last-child(n+2):before {
      content: '';
      display: block;
      width: 2px;
      height: 100px;
      position: absolute;
      left: -20px;
      background-color: red;
    }
    <div class="box-container">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>