You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确选中class为table__row的首、尾元素并添加自定义样式

问题原因

first-of-type伪类的匹配规则是按照HTML元素类型筛选同层级下的第一个对应元素,不会参考类名。你的.table父容器下第一个子元素是<div class="table__headers">,和.table__row一样都是div元素,所以.table__row:first-of-type实际匹配的是第一个div(也就是表头元素),但它没有.table__row类,所以样式不生效;而最后一个同层级div刚好是.table__row元素,所以last-of-type样式正常触发。

解决方案

方案1:无需修改HTML结构

可以用相邻兄弟选择器匹配第一个.table__row,最后一个继续用last-of-type即可,SCSS写法如下:

.table {
  // 原有样式保持不变
  &__row {
    background: #f8f8fa;
    // 匹配紧跟表头后的第一个行元素
    &:is(.table__headers + &) {
      border: solid 1px red;
    }
    &:last-of-type {
      border: solid 1px blue;
    }
  }
}

如果你的项目仅需要兼容高版本浏览器(Chrome 111+、Firefox 113+),也可以用支持类筛选的nth-child写法,逻辑更直观:

.table {
  &__row {
    &:nth-child(1 of &) {
      border: solid 1px red;
    }
    &:nth-last-child(1 of &) {
      border: solid 1px blue;
    }
  }
}

方案2:调整HTML结构(更推荐,扩展性更强)

新增.table__body容器包裹所有行元素,从结构上隔离表头和数据行:

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

调整后直接使用first-of-type/last-of-type即可正常匹配,兼容性和可维护性更好:

.table {
  // 原有样式保持不变
  &__row {
    background: #f8f8fa;
    &:first-of-type {
      border: solid 1px red;
    }
    &:last-of-type {
      border: solid 1px blue;
    }
  }
}

内容的提问来源于stack exchange,提问作者Riza Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:18:03