Search code examples
htmlcsscss-animationscss-transitionscss-transforms

Transition/animation not working if element is before the toggle


I want to animate the visibility of a few elements, and I isolated this code to show that only the elements after the toggle work, not the ones before (the thing I would need): is there any explanation for this behaviour???
I'm using Chrome latest version for the tests.

.element-1 {
    transform-origin: top;
    transform: scaleY(1);
    transition: all 0.5s ease-out;
    overflow: hidden;
}

input[type="checkbox"]:checked~.element-1 {
    transform: scaleY(0);
    transition: all 0.5s ease-in;
}
<div class="element-1">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
</div>

<div class="element-1">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
</div>

<input type="checkbox" id="toggle">
<label for="toggle">Toggle Element</label>

<div class="element-1">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
</div>

<div class="element-1">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
</div>


Solution

  • ~ selector selects only subsequent not previous that's why it doesn't work for previous siblings. You can read more about this here.

    However here is workaround to select previous siblings as well, you need to add wrapper and use :has to select all siblings.

    .element-1 {
      transform-origin: top;
      transform: scaleY(1);
      transition: all 0.5s ease-out;
      overflow: hidden;
    }
    .wrapper:has(input:checked) .element-1 {
      transform: scaleY(0);
      transition: all 0.5s ease-in;
    }
    <div class="wrapper">
      <div class="element-1">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
      </div>
    
      <div class="element-1">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
      </div>
    
      <input type="checkbox" id="toggle">
      <label for="toggle">Toggle Element</label>
    
      <div class="element-1">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
      </div>
    
      <div class="element-1">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <p>Nulla faucibus nisi nec ullamcorper finibus.</p>
      </div>
    
    </div>