首页 > 解决方案 > 使用纯 CSS 切换表格单元格

问题描述

有没有办法使用 CSS 没有 JavaScript 来切换(显示/隐藏)表格列或行?

我已经完成了以下代码,它适用于 div 但不适用于列或行

    <label for="trigger">Toggle box</label>

<input id="trigger" type="checkbox">
<div class="box">
Harry I've got Toggled
</div>

<table>
    <thead>
        <tr>
            <th colspan="2">The table header</th>
        </tr>
    </thead>
    <tbody>
        <tr >
           <td class="box"> I am a column1, I've got same class but sadly did not get toggled! do you know why?</td>
            <td>  I am a column 2 I don't have any class</td>
        </tr>
    </tbody>
</table>
<style>

.box {
  display: none;
}
#trigger:checked + .box {
  display: block;
}
table,
td {
    border: 1px solid #333;
}

thead,
tfoot {
    background-color: #333;
    color: #fff;
}
</style>

如何切换表格的列或行?

标签: csstoggle

解决方案


您的选择器不正确,应该是#trigger:checked ~table .box

首先寻找下一个兄弟姐妹,然后寻找该兄弟姐妹的孩子(如果它站在里面)。

.box {
  display: none;
}
#trigger:checked ~ .box,
#trigger:checked ~table .box {
  display: block;
}
table,
td {
    border: 1px solid #333;
}

thead,
tfoot {
    background-color: #333;
    color: #fff;
}
<label for="trigger">Toggle box</label>

<input id="trigger" type="checkbox">
<div class="box">
Harry I've got Toggled
</div>

<table>
    <thead>
        <tr>
            <th colspan="2">The table header</th>
        </tr>
    </thead>
    <tbody>
        <tr >
           <td class="box"> I am a column1, I've got same class but sadly did not get toggled! do you know why?</td>
            <td>  I am a column 2 I don't have any class</td>
        </tr>
    </tbody>
</table>


推荐阅读