有没有一种方法可以选择仅CSS相邻的非div元素同级的最后一个div元素?

时间:2020-05-27 15:32:55

标签: html css css-selectors

Consider my codepen experiment

我认为:last-child和类似的伪选择器仅针对同一兄弟元素。在我的实验中,这将是一个div元素。但是在我的代码笔中,似乎如果在最后一个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>

1 个答案:

答案 0 :(得分:0)

您可以使用:last-of-type 来做到这一点,this 代表一组兄弟元素中其类型的最后一个元素。

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

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

相关问题