Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change background color of checkbox in css

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.
enter image description here

If i unchecked the checkbox it will be look like below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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

>Solution :

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:

.main:has(input[id='maincheck']:checked) {
  background-color: #ccc;
}
<div class="main">
  <input type="checkbox" id="maincheck">item title
</div>

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:

.wrap {
  position: relative;
}

input[id='maincheck'] {
  position: absolute;
}

label[for='maincheck'] {
  margin-left: 1.5rem;
}

input[id='maincheck']:checked+.main {
  background-color: #ccc;
}
<div class="wrap">
  <input type="checkbox" id="maincheck" />
  <div class="main">
    <label for="maincheck">item title</label>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading