【问题标题】:How to target first and last elements of a class如何定位类的第一个和最后一个元素
【发布时间】:2021-11-07 05:58:04
【问题描述】:

我有一个简单的表格标记:

<div class="table">
  <div class="table__headers"></div>
  <div class="table__row"></div>
  <div class="table__row"></div>
</div>

我已经使用这个 CSS 设置了它的样式:

<style lang="scss" scoped>
.grid {
    display: grid;
    grid-gap: 0.5rem;
}

.table {
    &__headers,
    &__row {
        @extend .grid;
        padding: 0.5rem 0.75rem;

        :first-child {
            text-align: start;
        }

        :last-child {
            text-align: end;
        }

        p {
            font-size: 0.8rem;
            font-weight: bold;
            text-align: center;
            margin: 0;
        }
    }

    &__row {
        background: #f8f8fa;
    }
}
</style>

我唯一的问题是我无法专门定位 firstlast table__row 元素,因此我可以设置不同的样式。

以下不起作用:

&__row:first-of-type {
  border: solid 1px red;
}

&__row:last-of-type {
  border: solid 1px blue;
}

last-of-type 有效,但不是第一个类型。任何帮助将不胜感激!

谢谢,

【问题讨论】:

  • 因为这不是这些伪类的工作方式(如您所料)。一个元素必须匹配所有条件才能被选择器选中。由于table__row 绝不是其父级中的第一个 div,因此它永远不会匹配.table__row:first-of-type 选择器。

标签: javascript vue.js sass


【解决方案1】:

:first-of-type 不起作用的原因是因为它的功能等同于 :nth-child(1),而由于前面的 &lt;div&gt; 元素,您需要的是 :nth-child(2)

这些选择器旨在使用元素 (TagName) 而不是类。

【讨论】:

  • 但是,虽然很容易知道第一行是什么数字 (2),但如果表格不是静态的,最后一行就不那么容易了。
  • 不必知道最后一个数字。 :last-of-type 在这种情况下效果很好。
【解决方案2】:

这是一个 JavaScript 解决方案:

let rows = document.querySelectorAll(".table__row"); // Get all rows into an "array-like" object
rows[0].classList.add("firstRow");                   // Get and style first row
rows[rows.length-1].classList.add("lastRow");        // Get and style last row
.firstRow { background-color:red; }
.lastRow { background-color:green; }
<div class="table">
  <div class="table__headers"></div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
  <div class="table__row">blah</div>
</div>

【讨论】:

  • 是的,我担心它会变成这样 :(,没有 CSS 唯一的解决方案(问朋友)。
猜你喜欢
  • 2015-08-22
  • 2021-06-08
  • 1970-01-01
  • 2016-02-22
  • 2012-06-11
  • 1970-01-01
  • 2015-08-31
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多