In this example, we have a <div>
element, the content of which can be toggled between shown and hidden by clicking or pressing any key.
HTML
<p>
Click anywhere on the screen or press any key to toggle the
<code><div></code> content between hidden and showing.
</p>
<div>
This is a <code><div></code> element that animates between
<code>content-visibility: hidden;</code>and
<code>content-visibility: visible;</code>. We've also animated the text color
to create a smooth animation effect.
</div>
CSS
In the CSS we initially set content-visibility: hidden;
on the <div>
to hide its content. We then set up @keyframe
animations and attach them to classes to show and hide the <div>
, animating content-visibility
and color
so that you get a smooth animation effect as the content is shown/hidden.
div {
font-size: 1.6rem;
padding: 20px;
border: 3px solid red;
border-radius: 20px;
width: 480px;
content-visibility: hidden;
}
/* Animation classes */
.show {
animation: show 0.7s ease-in forwards;
}
.hide {
animation: hide 0.7s ease-out forwards;
}
/* Animation keyframes */
@keyframes show {
0% {
content-visibility: hidden;
color: rgb(0 0 0 / 0%);
}
100% {
content-visibility: visible;
color: rgb(0 0 0 / 100%);
}
}
@keyframes hide {
0% {
content-visibility: visible;
color: rgb(0 0 0 / 100%);
}
100% {
content-visibility: hidden;
color: rgb(0 0 0 / 0%);
}
}
JavaScript
Finally, we use JavaScript to apply the .show
and .hide
classes to the <div>
as appropriate to apply the animations as it is toggled between shown and hidden states.
const divElem = document.querySelector("div");
const htmlElem = document.querySelector(":root");
htmlElem.addEventListener("click", showHide);
document.addEventListener("keydown", showHide);
function showHide() {
if (divElem.classList[0] === "show") {
divElem.classList.remove("show");
divElem.classList.add("hide");
} else {
divElem.classList.remove("hide");
divElem.classList.add("show");
}
}
Result
The rendered result looks like this: