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

CSS Grid实现非表头行hover时边框变红的问题求助

问题

我想创建一个简易表格样式,需求是:仅让不含grid headers-row类的数据行在hover时,整行的黑色边框变为红色;带有grid headers-row类的表头行hover时无任何变化。以下是我当前使用的CSS和HTML代码:

.grid {
  display: grid;
  grid-template-columns: 15% 10% 25% 25% 25%;
  > * {
    height: 5.125rem;
    text-align: left;
    &:first-child {
      border-radius: 0.5rem 0 0 0.5rem;
      text-align: left;
      padding-left: 1rem;
    }

    &:last-child {
      border-radius: 0 0.5rem 0.5rem 0;
    }
    margin-bottom: 0.5rem;
  }
  &:not(.headers-row) > * {
    display: flex;
    flex-direction: column;
    align-items: left;
    justify-content: center;
    &:first-child {
      justify-content: center;
    }
    border: 1px solid black;
    border-left: 0;
    border-right: 0;
    &:first-child {
      border-left: 1px solid black;
    }
    &:last-child {
      border-right: 1px solid black;
    }
  }
}
<div class="grid headers-row">
  <span>Name</span>
  <span>Age</span>
  <span>Address</span>
  <span>Status</span>
  <span>QRSCode</span>
 </div>
 <div class="grid">
  <span>
   <div>John Doe</div>
   <div>jdoe@jdoe.com</div>
  </span>
  <span>67</span>
  <span>
     <div>Address 1</div>
     <div>Address 2</div>
  </span>
  <span><div>Status</div></span>
  <span><div>1234567</div></span>
</div>
解决方案

只需在现有CSS中添加一行hover状态的样式规则,就能精准实现需求:

.grid {
  display: grid;
  grid-template-columns: 15% 10% 25% 25% 25%;
  > * {
    height: 5.125rem;
    text-align: left;
    &:first-child {
      border-radius: 0.5rem 0 0 0.5rem;
      text-align: left;
      padding-left: 1rem;
    }

    &:last-child {
      border-radius: 0 0.5rem 0.5rem 0;
    }
    margin-bottom: 0.5rem;
  }
  &:not(.headers-row) > * {
    display: flex;
    flex-direction: column;
    align-items: left;
    justify-content: center;
    &:first-child {
      justify-content: center;
    }
    border: 1px solid black;
    border-left: 0;
    border-right: 0;
    &:first-child {
      border-left: 1px solid black;
    }
    &:last-child {
      border-right: 1px solid black;
    }
  }
  /* 核心新增规则:非表头行hover时,子元素边框变红 */
  &:not(.headers-row):hover > * {
    border-color: red;
  }
}

原理说明

  • 使用&:not(.headers-row):hover > *选择器,只选中不带headers-row类的.grid元素在hover状态下的所有子元素,将它们的边框颜色改为红色,实现整行边框变红的效果。
  • 带有headers-row类的表头行,因为被:not(.headers-row)排除,hover时不会触发任何样式变化,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 06:03:17