Search code examples
htmlcsscheckboxcss-transforms

Why can't my checkbox affect my div contents?


I have a checkbox and a div element. When I click on the checkbox, the contents of the div elements are supposed to rotate to form a cross. But it does not do that. Below is the code

:root {
  --main-color: red;
  --secondary-color: blue;
  --dark-color: #444;
  --light-color: #fafafa;
}

body {
  font-family: 'Montserrat', sans-serif;
  text-align: justify;
  margin: 0px;
  display: grid;
  place-items: center;
  font-size: 18px;
}

input {
  box-sizing: border-box;
}

.toggle {
  height: 100px;
  width: 100px;
  border: 1px solid black;
}

span {
  height: 20px;
  width: 100px;
  display: grid;
  place-items: center;
  background-color: blue;
  margin: 5px 0;
}

.check:checked~span {
  background: red;
}

.check:checked~.span-one {
  position: relative;
  top: 100%;
  transform: rotate(45deg);
  transition: 400ms;
}

.check:checked~.span-two {
  position: relative;
  opacity: 0;
  transition: 400ms;
}

.check:checked~.span-three {
  position: relative;
  bottom: 100%;
  transform: rotate(-45deg);
  transition: 400ms;
}
<input class="check" type="checkbox">
<div>
  <span class="span-one"></span>
  <span class="span-two"></span>
  <span class="span-three"></span>
</div>

It works without the div but I need the div for something else so I can't remove that.

How do I fix this?


Solution

  • :root {
      --main-color: red;
      --secondary-color: blue;
      --dark-color: #444;
      --light-color: #fafafa;
    }
    
    body {
      font-family: 'Montserrat', sans-serif;
      text-align: justify;
      margin: 0px;
      display: grid;
      place-items: center;
      font-size: 18px;
    }
    
    input {
      box-sizing: border-box;
    }
    
    .toggle {
      height: 100px;
      width: 100px;
      border: 1px solid black;
    }
    
    span {
      height: 20px;
      width: 100px;
      display: grid;
      place-items: center;
      background-color: blue;
      margin: 5px 0;
    }
    
    .check:checked ~ div span { /* We need to make the div the sibling instead of the span */
      background: red;
    }
    
    .check:checked ~ div .span-one {
      position: relative;
      top: 50px; /* Changed from 100% */
      transform: rotate(45deg);
      transition: 400ms;
    }
    
    .check:checked ~ div .span-two {
      position: relative;
      opacity: 0;
      transition: 400ms;
    }
    
    .check:checked ~ div .span-three {
      position: relative;
      bottom: 100%;
      transform: rotate(-45deg);
      transition: 400ms;
    }
    <input class="check" type="checkbox">
    <div>
      <span class="span-one"></span>
      <span class="span-two"></span>
      <span class="span-three"></span>
    </div>