Home > Mobile >  Can I change size of an other box with a button in it without using JavaScript?
Can I change size of an other box with a button in it without using JavaScript?

Time:03-03

I want to have a box (Card1) with a button in it (Button is in Card1) (see the code example) and change the size of the Card 2 and card 1 (make card 2 bigger and card 1 smaller).

But the trick is that I can’t use JavaScript. First of all, is it possible or not? And if it is, how?

#card1{
  width: 50%;
  background-color: red;
}
#card2{
  width: 50%;
  margin-top: 1%;
  background-color: green;
  height: 10%;
}
#button{
  background-color: yellow;
}
<div id="card1">
  I am card 1
  <div id="button">
    Click me and make card 2 bigger and card 1 smaller
  </div>
</div>

<div id="card2">
  I am card2
<div>

CodePudding user response:

You can achieve that by creating hidden checkbox, then when it's checked select any needed element that follows it (do not make it in inner DOM or after elements, as CSS can only select "future" nodes going from root)

Here I use checkbox state :checked and select all following elements with ~

#card1{
  width:50%;
  background-color:red;
  transition: width 300ms ease-in-out;
}
#card2{
  width:50%;
  margin-top:1%;
  background-color:green;
  height:10%;
  transition: width 300ms ease-in-out;
}
#button{
  background-color:yellow;
}

#hidden-checkbox:checked ~ #card1 {
  width: 25%;
}

#hidden-checkbox:checked ~ #card2 {
  width: 75%;
}
<input type="checkbox" id="hidden-checkbox"/>

<div id="card1">
  I am card 1
  <label for="hidden-checkbox" id="button">
    Click me and make card 2 bigger and card 1 smaller
  </label>
</div>

<div id="card2">
  I am card2
<div>

CodePudding user response:

You can use Input type checkbox and inside the label, you can use card1 div, and using CSS checked selector (:checked) you can check the box and set the new width of the div2.

  • Related