简体   繁体   中英

Styling label based on child div

是否可以根据是否使用CSS检查输入来设置标签样式,或者我是否使用javascript卡住了?

<label class="filterButton"> <input name="RunandDrive" type="checkbox" value="1"> </label>

In order to style label with "checked" checkbox first of all you have to set up an ID for the input"Checkbox" id="qid" and put the for label this code for="qid" to guid the label for this checkbox input

That's all!

 input[type=checkbox] + label { color: #ccc; font-style: italic; } input[type=checkbox]:checked + label { color: #f00; font-style: normal; } 
 <input name="RunandDrive" type="checkbox" value="1" id="qid"> <label class="filterButton" for="qid"> Thsis will be styled</label> 

You can use the :checked pseudo-element to check wither the check box is checked or not. This works for the radio button and the check box.

The problem is that you want to select the parent of an element, but there is actually no parent selector in css. A work around is to put the label element after ( or before ) the input element and use the appropriate selector. In this case I put the label element after the input element and use the + selector.

 input[type=checkbox]+label { background-color: green; } input[type=checkbox]:checked+label { background-color: red; } 
 <input type="checkbox" id="ossm" name="ossm"> <label for="ossm">Click to turn RED!</label> 

But if you really must have the input element as a child of the label element, then yes, you have to stick to JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM