【问题标题】:Is there a way to select the last div element with adjacent non-div element siblings with CSS only?有没有办法仅使用 CSS 选择具有相邻非 div 元素兄弟的最后一个 div 元素?
【发布时间】:2020-05-27 23:44:27
【问题描述】:

Consider my codepen experiment

我认为 :last-child 和类似的伪选择器只针对同一个兄弟元素。在我的实验中,这将是一个 div 元素。但在我的 codepen 中,如果最后一个 div 元素之后有任何兄弟元素,那么最后一个 div 元素不再是最后一个子元素。

有没有办法仅使用 CSS 选择具有相邻非 div 元素兄弟的最后一个 div 元素?

现在,看来我唯一的结论是用不同的方式构建我的 HTML,以便最后一个 div 是其父元素中的最后一个元素。我希望有人有不同的答案!

.container {
  background-color: green;
}

.row {
  width: 90%;
  background-color: black;
  margin: 0 auto;
}

.row:not(:last-child) {
  margin-bottom: 8rem;
}

.row::after {
  content: "";
  clear: both;
  display: table;
}

.row .col-1-of-2 {
  float: left;
  background-color: orangered;
  color: #fff;
  width: calc((100% - 6rem)/2);
}

.row .col-1-of-2:not(:last-child) {
  margin-right: 6rem;
}

h1 {
  text-align: center;
}
<div class="container">
  <div class="row">
    <div class="col-1-of-2">Col 1 of 2</div>
    <div class="col-1-of-2">Col 1 of 2</div>
  </div>
  <div class="row">
    <div class="col-1-of-2">Col 1 of 2</div>
    <div class="col-1-of-2">Col 1 of 2</div>
  </div>
  <h1>Test</h1>
</div>

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    您可以使用:last-of-type 做到这一点,它表示一组同级元素中其类型的最后一个元素。

    所以你的最终代码应该是这样的:

    .container {
      background-color: green;
    }
    
    .row {
      width: 90%;
      background-color: black;
      margin: 0 auto;
    }
    
    .row:not(:last-of-type) {
      margin-bottom: 8rem;
    }
    
    .row::after {
      content: "";
      clear: both;
      display: table;
    }
    
    .row .col-1-of-2 {
      float: left;
      background-color: orangered;
      color: #fff;
      width: calc((100% - 6rem)/2);
    }
    
    .row .col-1-of-2:not(:last-child) {
      margin-right: 6rem;
    }
    
    h1 {
      text-align: center;
    }
    <div class- "container">
      <div class="row">
        <div class="col-1-of-2">Col 1 of 2</div>
        <div class="col-1-of-2">Col 1 of 2</div>
      </div>
      <div class="row">
        <div class="col-1-of-2">Col 1 of 2</div>
        <div class="col-1-of-2">Col 1 of 2</div>
      </div>
      <h1>Test</h1>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2011-10-27
      • 2012-07-11
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多