CSS-Selektor auf ein Element außerhalb des Label-Containers?

Gibt es eine Möglichkeit mit reinem CSS ein Element außerhalb eines input/label Containers anzusprechen?

<div>
<div class="labelcontainer">
    <label for="toggle">Toggle</label>
    <input type="checkbox" id="toggle" class="visually-hidden">
<div>
    <div class="container2"></div>
</div>

Ich möchte, wenn das Label checked ist, das css von container2 ändern. Ich glaube aber, das geht nicht oder?

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
9 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Niklas373
1 year ago

Unfortunately, there is no way to address an element outside the input/label container with pure CSS. This is because CSS can only be applied to elements within the hierarchical structure of the HTML document.

In this case, however, you could use JavaScript to achieve the desired behavior.

EinAlexander
1 year ago

Is there a way to address an element outside an input/label container with pure CSS?

Sure, no problem.

           
hello world

Alex

verreisterNutzer
1 year ago

No, I can’t. You need to use JS. This would then be the case (code not tested):

   
                   
   

CSS

.container2 {
    background-color: blue;
}

.container2.checked {
    background-color: red;
}

JS

const toggle = document.getElementById('toggle');
const container2 = document.querySelector('.container2');

toggle.addEventListener('change', function() {
  if (this.checked) {
    container2.classList.add('checked');
  } else {
    container2.classList.remove('checked');
  }
});
jessxs
1 year ago

I would recommend you for modifying JavaScript…is also quite easy and if it’s mostly just about css changes, this is hardly a problem for you.

jessxs
1 year ago
Reply to  Tababab

Is it a platform for practicing or learning or what kind of one?

NackterGerd
1 year ago

What you would like to do would be based on programming.

However, as you can’t program HTML and CSS, you need to try a programming language for your special requests.