I have one checkbox inside div. The div class name is main.I am trying to set the background color to main classname when i checked the checkbox. But not able to set background color to .main classname.
If i checked the checkbox it will be look like below.
If i unchecked the checkbox it will be look like below.
HTML:
<div class="main">
<input type="checkbox" id="maincheck">{{item.title}}
</div>
CSS:
.main input[id='maincheck']:checked:after{
background-color: #ccc;
}
How to achieve using CSS? Demo: https://stackblitz.com/edit/angular-checkbox-example-mhvnkb?file=app%2Fapp.component.html
2
Answers
Sounds like you want to change the background colour of the checkbox’s parent element. This can be rephrased as ‘if .main contains a checked checkbox then…‘. In CSS you could use the
:has()
pseudo-class to select an element that has a certain child:But note that at the time of writing this is NOT yet supported in Firefox. (See https://caniuse.com/css-has)
An alternative would be to move the checkbox to before its parent. Then you can use the next-sibling combinator (
+
) to select the div that directly follows a checked checkbox:You can’t directly change the parent element’s style using only CSS, so you’d have to use JavaScript or jQuery.
Here’s a JavaScript approach:
when you check the checkbox, the background colour of the .main div will change to #ccc, and when you uncheck it, the background will revert to transparent.