CSS - Animate display none, block and opacity

PloMar
Posts: 48

CSS - Animate display none, block and opacity

I have a Div and a Button that uses JavaScript to alternate the class of the Div to "hide" and "show". The "hide" class has "display:none;" to hide the Div (and opacity 0), and the "show" class has "display:block;" to show the Div (and opacity 1).
Is it possible to animate the display none /block and opacity using only CSS?
This is the code:

Code: Select all

<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Title</title> <style> #cnt1 { position: relative; margin: 4px auto; background:#eee; } #cnt1.hide { opacity : 0; display: none; } #cnt1.show { opacity:1; display: block; width: 75%; height: 150px; } </style> </head> <body> <div id="cnt1" class="show"> <p>Content to be displayed</p> <p>Other paragraph with content to be displayed</p> </div> <button id="btn1">Hide</button> <script> // get the htmll elements var cnt1 = document.getElementById('cnt1'); var btn1 = document.getElementById('btn1'); // register click event to #btn1 that alternate class to #cnt1, and changes #btn1 text btn1.addEventListener('click', function() { if(cnt1.className == 'show') { cnt1.className = 'hide'; btn1.innerHTML = 'Show' } else { cnt1.className = 'show'; btn1.innerHTML = 'Hide'; } }); </script>

MarPlo
The "display: none;" and "display: block;" are executed instantly, from what I know, you cannot animate them with only CSS. But to achieve the animation hide /show effect with CSS, you can use "transition" property and set the "height" and "width" to 0 for ".hide" (it will animate also the opacity).
Test this code:

Code: Select all

<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Title</title> <style> #cnt1 { position: relative; margin: 4px auto; background:#eee; } #cnt1.hide { opacity : 0; width: 0; height:0; transition: height, 1s linear; } #cnt1.hide * { display: none; /* needed to hide the content in that Div */ } #cnt1.show { opacity:1; width: 75%; height:150px; transition: height, 1s linear; } </style> </head> <body> <div id="cnt1" class="show"> <p>Content to be displayed</p> <p>Other paragraph with content to be displayed</p> </div> <button id="btn1">Hide</button> <script> // get the htmll elements var cnt1 = document.getElementById('cnt1'); var btn1 = document.getElementById('btn1'); // register click event to #btn1 that alternate class to #cnt1, and changes #btn1 text btn1.addEventListener('click', function() { if(cnt1.className == 'show') { cnt1.className = 'hide'; btn1.innerHTML = 'Show' } else { cnt1.className = 'show'; btn1.innerHTML = 'Hide'; } }); </script> </body> </html>
Demo:

Content to be displayed

Other paragraph with content to be displayed


Similar Topics