CSS to display:none whilst animating collapsible container

1 day ago 2
ARTICLE AD BOX

I have an animated collapsible nav. I do not want the content rendered whilst it is expanding or contracting because it's expensive to render/re-render during the animation (it's causing rendering lag and opacity/visibility aren't enough). Put another way, it should be display:none whilst the nav is animating/its collapsed.

I can achieve this through setTimeout() in JavaScript but I'm wondering if there is a pure CSS solution to this problem (maybe with transition-behavoir: allow-discrete?)

Here is my JavaScript solution:

document.querySelector("header").addEventListener("click", () => { document.querySelector("nav").toggleAttribute("opened"); }); // I wish to move everything below into CSS if possible document.querySelector("header").addEventListener("click", () => { if (document.querySelector("div").hasAttribute("displayed")) { document.querySelector("div").toggleAttribute("displayed"); } else { setTimeout(() => document.querySelector("div").toggleAttribute("displayed"), 500); } }); nav { background: grey; display: flex; flex-direction: column; height: 20px; transition: height 0.5s; width: 500px; } nav[opened] { height: 200px; } header { background: blue; height: 20px; } div { background: red; display: none; flex: 1; } div[displayed] { display: block; } <nav> <header></header> <div></div> </nav>
Read Entire Article