首页 > 解决方案 > 如何使用css将边框添加到带有th的tr

问题描述

我已经建立了一个网页,其中包含一些带有侧标题的表格。这是我的标记:

<table id="talents">
    <thead>
        <!-- ... -->
    </thead>
    <tbody>
        <tr>
            <th scope="rowgroup" rowspan="3">Investigator</th>
            <td>At 3rd: Expanded Inspiration (Ex)</td>
            <td>Free insp. on Diplomacy, Heal, Perception, Profession, Sense Motive.</td>
        </tr>
        <!-- more trs falling into the above rowgroup -->
        <tr>
            <th scope="rowgroup" rowspan="4">Rogue</th>
            <td>At 2nd: Positioning Attack</td>
            <td>Once per day move up to 30ft. to spot adjacent to creature attacked.</td>
        </tr>
        <!-- more trs falling into the above rowgroup -->
    </tbody>
</table>

这是呈现的表格: 在此处输入图像描述

我想对这些border-top行组之间的边框进行样式设置,比如将 a 添加到包含<th>Rogue</th>. 如果可能的话,我对纯 CSS 解决方案很感兴趣——一种无需在行中添加类或 id<th>或其他东西的方法。

顺便说一句,实验性的 :has() 选择器似乎很简单:

tbody tr:has(> th) { border-top: 2px solid black; }

仍然没有浏览器支持:has(). 有支持的替代方案吗?

标签: htmlcss

解决方案


你可以使用这样的东西,

table {
  border-collapse: collapse;
}

tbody tr>th,
tbody tr>th~td {
  border-top: 2px solid black;
}
<table id="talents">
  <thead>
    <!-- ... -->
  </thead>
  <tbody>
    <tr>
      <th scope="rowgroup" rowspan="2">Investigator</th>
      <td>At 3rd: Expanded Inspiration (Ex)</td>
      <td>Free insp. on Diplomacy, Heal, Perception, Profession, Sense Motive.</td>
    </tr>
    <tr>
      <td>At 3rd: Expanded Inspiration (Ex)</td>
      <td>Free insp. on Diplomacy, Heal, Perception, Profession, Sense Motive.</td>
    </tr>
    <!-- more trs falling into the above rowgroup -->
    <tr>
      <th scope="rowgroup" rowspan="4">Rogue</th>
      <td>At 2nd: Positioning Attack</td>
      <td>Once per day move up to 30ft. to spot adjacent to creature attacked.</td>
    </tr>
    <!-- more trs falling into the above rowgroup -->
  </tbody>
</table>


推荐阅读