Home > Software engineering >  How to access from child checkbox to child class in different parent divs?
How to access from child checkbox to child class in different parent divs?

Time:11-26

How can i rotate all 3 pictures on click on checkbox?

I am trying with ~ but it only affects on the image where checkbox is.

HTML:

<div class="img-wrapper">
  <img class="img" src="https://via.placeholder.com/300" />
</div>

<div class="img-wrapper">
  <input class="checkbox" type="checkbox" id="rotate">
  <label class="label-checkbox" for="rotate">Rotate</label>

  <img class="img" src="https://via.placeholder.com/300" />
</div>

<div class="img-wrapper">
  <img class="img" src="https://via.placeholder.com/300" />
</div>

SCSS:

.checkbox:checked {
        ~ .img {
          transform: rotate(180deg);
        }
    }

CodePudding user response:

You could do it with javascript, something like this:

if ($("#rotate").is(':checked')) {
    $(".img-wrapper img").css("transform", "rotate(180deg)");
}

or

if ($("#rotate").is(':checked')) {
    $(this).parent().find("img").css("transform", "rotate(180deg)");
}

Other option :has
https://caniuse.com/?search=:has

CodePudding user response:

If we have :has() pseudo selector today, it might be

.something:has(input:checked) img {
  transform: rotate(180deg);
}

As far as we haven't yet, you should lift up the checkbox for it

<input class="checkbox" type="checkbox" id="rotate">

<div class="img-wrapper">
  <img class="img" src="https://via.placeholder.com/300" />
</div>

<div class="img-wrapper">
  <label class="label-checkbox" for="rotate">Rotate</label>

  <img class="img" src="https://via.placeholder.com/300" />
</div>

<div class="img-wrapper">
  <img class="img" src="https://via.placeholder.com/300" />
</div>

Then you can select <img>s using

input:checked ~ .img-wrapper > img {
  transform: rotate(180deg);
}

And you can draw a custom checkbox by hiding original <input> and styling on the <label>

  • Related