Home > Enterprise >  CSS change a class display by checking some checkbox
CSS change a class display by checking some checkbox

Time:06-21

I'm trying changing a CSS class property by checking a checkbox, but it doesn't work... Can you help me?

My code:

<body>
<style>
    #test:checked~#title {
        display: none;
    }

    .reverse-flexbox {
        display: flex;
        flex-direction: column-reverse;
        align-items: flex-start;
    }
</style>
<div>
    <div >
        <h1 id="title">Just a text</h1>
        sky is blue
    </div>
    <div >
        <h1 id="title">Just a text</h1>
        i like stackoverflow
    </div>
    <input type="checkbox" id="test" />
    <h1 id="title">Just a text</h1>
    <div>Something else</div>
</div>
</body>

</html>

CodePudding user response:

~ only works for the downward siblings which are below the element #test. #title is above #test, so that's why your styles do not apply.

If you don't want to change element positions, and still want to use ~, you can move #title up for style application, and then use the reverse directions of the flexbox to show #title is above #test (only in display).

For multiple h1 case, you also need to add them below #test checkbox

<html lang="pt-br">

<body>
  <style>
    #test:checked~div > #title {
      display: none;
    }
    
    .reverse-flexbox {
      display: flex;
      flex-direction: column-reverse;
      align-items: flex-start;
    }
  </style>
  <div>
     <div >
       <input type="checkbox" id="test" />
       <div>
          <h1 id="title">Just a text 1</h1>
       </div>
       <div>
          <h1 id="title">Just a text 2</h1>
       </div>
       <div>
          <h1 id="title">Just a text 3</h1>
       </div>
     </div>
     <div>Something else</div>
  </div>
</body>

</html>

CodePudding user response:

You have to use input tag first then you can use another html tag to make checked pseudo class working and you can use flexbox to order the html tags.

.form_group{
  display: flex;
  flex-direction: column;
} 
#test{
  order: 2;
}
#title{
  order: 1;
}
#test:checked~#title {
      display: none;
}
<div >   
  <input type="checkbox" id="test" />
<h1 id="title">Just a text</h1> 
</div>

  • Related