CSS toggle box

by Greg Bowler

HTML

<p>
    This shows how a checkbox can be used to toggle a table cell, without any JavaScript or HTTP calls. Both columns should be rendered on the server, and one is hidden via CSS.
</p>

<input type="checkbox" id="toggle-control" />
<label for="toggle-control">
    <span class="blue">Blue</span>
    <span class="red">Red</span>
</label>

<table>
    <tr>
        <th>Col1</th>
        <th>Col2</th>
        <th>Col3</th>
        <th class="a">Col4A</th>
        <th class="b">Col4B</th>
    </tr>
    <tr>
        <td>M</td>
        <td>F</td>
        <td>L</td>
        <td class="a">Z</td>
        <td class="b">O</td>
    </tr>
    <tr>
        <td>V</td>
        <td>D</td>
        <td>T</td>
        <td class="a">P</td>
        <td class="b">M</td>
    </tr>
    <tr>
        <td>A</td>
        <td>I</td>
        <td>F</td>
        <td class="a">G</td>
        <td class="b">L</td>
    </tr>
</table>

SCSS

$blue = #ddf;
$red = #fdd;

table {
    .a {
        background: $blue;
    }
    .b {
        background: $red;
    }
    
   tr {
       th {
            border-bottom: 2px solid red;
            padding: 8px;
       }
        td {
            background: #ddd;
            text-align: center;
        }
    }
}

input#toggle-control {
    display: none;
    
    &:checked {
        ~ label {
            background: $red;
                
                span.red {
                    opacity: 1;
                }
                span.blue {
                    opacity: 0.2;
                }
        }
        
        ~ table {
            .a {
                display: none;
            }
                .b {
                    display: table-cell;
                }
        }
    }
        
    ~ label {
        display: block;
        width: 128px;
        background: $blue;
        padding: 8px;
        margin: 16px;
        border-radius: 4px;
        overflow: hidden;

            span {
                display: block;
                float: left;
                width: 50%;
            }
            span.red {
                opacity: 0.2;
                text-align: right;
            }
    }
        
        ~ table {
            .b {
                display: none;
            }
        }
}