首页 > 解决方案 > 如何将border-bottom应用于最后一个不为空的?

问题描述

<table>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
    <tr>
        <th>A</th>
        <th>B</th>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
</table>

我想将border-bottom应用于这种<table>但我不知道如何选择最后一个不为空<tr>的,还有其他方法吗?

PS:不知道里面有多少<td>或者是空<tr><table>


换句话说,我想要这张桌子底部的红色边框 https://jsfiddle.net/37L334hj/68/

标签: htmlcsscss-selectors

解决方案


做复杂的向后看的 CSS 选择器并不是一个很好的方法。如果您的表格稍微复杂一点,使用 Next Sibling 和 General Sibling CSS 选择器会很快变得非常难看。你能用一些JavaScript吗?这将是微不足道的,只有 2 或 3 行。另请注意,您实际上不能将border参数添加到 a tr,但可以添加到td. 对于这个例子,我只是做了一个 1px 的盒子阴影。

let rows = document.querySelectorAll('tr:not(.empty-row)');
let lastRow = rows[rows.length - 1];

lastRow.setAttribute( 'style', 'box-shadow: 0 1px 0 red' );
<table>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
    <tr>
        <th>A</th>
        <th>B</th>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
    <tr>
        <td>c</td>
        <td>d</td>
    </tr>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
</table>

综上所述,如果您只需要在表格底部添加边框,您可以在表格底部添加边框并将.empty-row类设置为display: none;吗?

table { border-bottom: 1px solid green; }
tr.empty-row { display: none; }
<table>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
    <tr>
        <th>A</th>
        <th>B</th>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
    <tr>
        <td>c</td>
        <td>d</td>
    </tr>
    <tr class="empty-row"></tr>
    <tr class="empty-row"></tr>
</table>


推荐阅读