2

I have one div which have one checkbox, I am trying to change color of div when checkbox checked - unchecked using HTML CSS only without using JavaScript. But as CSS doesn't support backtrace I am not sure how to achieve this.

CSS:

.content {
  height: 50px;
  width:50px;
  border: 1px solid black;
}

HTML:

<div class="content">
  <input type="checkbox">
</div>
Fletcher Ripp
  • 1,157
  • 10
  • 18
Sandesh Sardar
  • 1,431
  • 5
  • 23
  • 43
  • Any reason why you can't use javascript? Depending on your structure and desired result, you could put the style in the checkbox in a way that "overflow" and take the div space...not really a good practice though. – Bruno Monteiro Jul 22 '19 at 04:45
  • @BrunoMonteiro There is no as such big reason, but we are creating on library which has some limitations (for various business reasons) in which we are trying to achieve most of the thing using pure CSS – Sandesh Sardar Jul 22 '19 at 04:47
  • I see...as far as I know, it is not possible to change the style of a parent component based in the child component. So you either use JS or some kind of "overflow" solution :( – Bruno Monteiro Jul 22 '19 at 04:49
  • If you use JS you can add a data-attribute to the div that is true/false matching the checkbox value. Then use css to style using that attribute. – mep2664 Jul 22 '19 at 04:51
  • Possible duplicate of [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – Cuong Le Ngoc Jul 22 '19 at 04:51

1 Answers1

4

I have wrapped the checkbox and the span inside a label and then added the CSS below:

label {
  height: 50px;
  width: 50px;
  border: 1px solid black;
  display: inline-block;
  position: relative;
}

.content {
  display: inline-block;
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  z-index: -1;
  left: 0;
}

input:checked+span {
  background-color: red
}
<label for="check">
  <input type="checkbox">
  <span class="content">
   
  </span>
</label>
Xenio Gracias
  • 2,585
  • 1
  • 7
  • 16
  • Since the label wrapps around the checkbox, it doesn't need the `for` attribute. – cloned Jul 22 '19 at 07:12
  • `label` is not allowed to contain `div`. This should be made into a `span` or something else from the [phrasing content](https://html.spec.whatwg.org/multipage/dom.html#phrasing-content-2) allowed inside of a label. – misorude Jul 22 '19 at 07:16
  • @misorude I have updated my ans. and thanks for the info – Xenio Gracias Jul 22 '19 at 09:43