Animate element with smooth fade-in on appearance, but instantly hide on disappearance

Viewed 85

I've got an element with opacity: 0.

When a certain selector matches, I would like opcacity to smoothly transition to 1.

When that selector no longer matches, I would like opacity to instantly revert to 0.

How do I do that?

PS No JS, of course.

.the {
  display: inline-block;
  border: 1px solid deepskyblue;
  background-color: lightblue;
  padding: 2px 5px;
  border-radius: 4px;
  
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  opacity: 0;
  pointer-events: none;
}

input:checked ~ .the {
  opacity: 1;
}
<label>
  <input type="checkbox">
  Show element
  
  <span class="the">
    I'm the element to animate!
  </span>
</label>

1 Answers

You can add transition to the :checked rule:

.the {
  display: inline-block;
  border: 1px solid deepskyblue;
  background-color: lightblue;
  padding: 2px 5px;
  border-radius: 4px;
  
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  opacity: 0;
  pointer-events: none;
}

input:checked ~ .the {
  transition: opacity .5s;
  opacity: 1;
}
<label>
  <input type="checkbox">
  Show element
  
  <span class="the">
    I'm the element to animate!
  </span>
</label>

Related