Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

html - Change checkbox label css property with checkbox checked

I have the following html:

  <label>
     <input type="checkbox" value="cb_val" name="cb_name">
     my checkbox text
  </label>

With CSS I added a background-color to the <label> tag.

label { background-color:#333; color:#FFF; }

Now I'd liked to change the background color of the label when the checkbox is checked. I know how to do it with javascript, but is there a way to to it just using CSS?

I have seen some solutions, but they use the adjacent sibling selector and only work when the label appears after the checkbox.

I still hope to fix this without javascript, does anyone have a clue?

UPDATE:

As I was afraid of, it cannot be done this way, so i must do it with JS, or achieve the same visual effect with a different HTML structure. I want to set the background color of the label and the textbox in one go, so I can go with a solution where the checkbox is placed absolute on top of the label. Good point PlantTheldea!

Or I can apply the background color to the label and the checkbox both.

Thanks everyone!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can achieve this with pure css like so,

<input type="checkbox" id="cb_1" value="cb_val" name="cb_name">
<label for="cb_1">
     my checkbox text
</label>

With this css,

label { background-color:#333; color:#FFF; }

input[type="checkbox"]:checked + label {
    background: brown;
}

JSFIDDLE

Keep in mind

The label has to be after the checkbox so you will need to style it around more to keep the same look you had.

Here is an option of styling it more to have the same appearance as you wanted, New fiddle. THIS DOES NOT involve positioning anything absolute, just some trickery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...