Line-through when checked over multiple td's using CSS

1.1k Views Asked by At

Im trying to do a linethrough over a label + checkbox both in a separate td.

In my example code I have created 2 tables:
Currently only table 1 is doing a line-through when checkbox = checked. I guess this is working because both elements share a td. Is there a way to fix this so table 2 can line-through instead of table 1? Thanks!

HTML:

<table id = "1">
    <tr>
        <td>
            <input id="oregano"  type="checkbox" class="checkedBox" />  
            <label for="oregano" class="checkedLabel">Oregano</label>  
        </td>
    </tr>
</table>

<table id = "2">
    <tr>
        <td><input id="oregano"  type="checkbox" class="checkedBox" /></td>        
        <td><label for="oregano" class="checkedLabel">Oregano</label></td>
    </tr>
</table>

Stylesheet:

.checkedBox:checked + .checkedLabel {
        text-decoration: line-through;
        color: blue
        }

Fiddle
http://jsfiddle.net/gdmpz506/

2

There are 2 best solutions below

0
Jukka K. Korpela On BEST ANSWER

It works in table 1 because there the input and label elements are siblings, i.e. children of the same element. It is irrelevant that the parent happens to be a td element. You are correctly using the “next sibling” operator +. (Here I’m assuming that you really want just the label struck out.)

The same is not possible when the input and label elements are not siblings, as they cannot be if they are in different td elements. There are no CSS selectors at present to handle such cases. You would need JavaScript to make checking a checkbox strike out the corresponding label.

2
Gabriele Petrioli On

That is because you have a different syntax for each table.

If you put the checkbox and label in the same td in the second table it will work just fine. (and of-course make the id unique so that the second label does not point to the first element..)

.checkedBox:checked + .checkedLabel {
    text-decoration: line-through;
    color: blue;
}
<table>
    <tr>
        <td>
            <input id="oregano-1" type="checkbox" class="checkedBox" />
            <label for="oregano-1" class="checkedLabel">Oregano</label>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td id="checktd">
            <input id="oregano-2" type="checkbox" class="checkedBox" />
            <label for="oregano-2" class="checkedLabel">Oregano 2</label>
        </td>
    </tr>
</table>

Demo at http://jsfiddle.net/gaby/gdmpz506/1/