Coming from https://stackoverflow.com/a/9334132/3779853: Let's assume a basic element that gets toggled programmatically. This could mean setting display to none/block or removing/inserting the element altogether.
$('#toggle').click(() => $('#square').toggle());
#square {
width: 50px;
height: 50px;
background: lightblue;
}
.animated {
animation: fade-in 1s;
}
@keyframes fade-in {
from { opacity: 0; }
to { opacity: 1; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">toggle</button>
<div id="square" class="animated"></div>
With a simple animation
, you can add a transition effect for when the element appears. How do you do the same thing for when the element disappears?
I do not want to add further classes, no :hover
, and no more Javascript code. In many JS frameworks, you can show/hide elements easily: .toggle()
(JQuery, as above), ng-if
(AngularJS), *ngIf
(Angular), conditional rendering (React), v-if
(VueJS) and so on. With above solution, a simple class="animated"
is enough to have it appear with custom animations. So I am looking for a pure CSS solution for fade out animation here, assuming this is a standard problem.