Mats
Mats

Reputation: 557

Selecting label element on check of nested radio button

What would be the correct CSS syntax to target the label wrapped around the input-field?

<div class="radio">
    <label>
        <input checked="checked" name="duration" type="radio" value="2" />
                2
    </label>
</div>

This is not working:

.radio input[type='radio']:checked label { outline: 1px solid gray; }

Upvotes: 0

Views: 2071

Answers (1)

Mr. Alien
Mr. Alien

Reputation: 157284

As CSS cannot select the text nodes, you will have to wrap the 2 using a label tag, and than you need to change your markup like below as CSS cannot select previous element.

<div class="radio">
    <input checked="checked" name="duration" type="radio" value="2" />
    <label>2</label>
</div>

And use adjacent selector like

.radio input[type='radio']:checked + label { 
    outline: 1px solid gray;
}

Demo


If you do not want to wrap the 2 in the label tag as I showed you previously than use span tag like

<div class="radio">
    <label>
        <input checked="checked" name="duration" type="radio" value="2" />
        <span>2</span>
    </label>
</div>

And selector like

.radio input[type='radio']:checked + span { 
    outline: 1px solid gray;
}

Demo 2

Upvotes: 7

Related Questions