I would like to make a css transition on an element which has display: none
set. Consider the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Transition From Hidden</title>
<style type="text/css">
div {
-webkit-transition-property: all;
-webkit-transition-duration: 2s;
}
div.hidden {
display: none;
opacity: 0;
}
div.from {
opacity: 0;
}
</style>
<script type="text/javascript">
function loaded() {
var e = document.getElementById("foo");
e.className = "from";
window.webkitRequestAnimationFrame(function(t) {
e.className = null;
});
}
</script>
</head>
<body onload="loaded()">
<div id="foo" class="hidden">
My test div
</div>
</body>
</html>
I would like to go from class="div.hidden"
to class=""
, i.e. from display: none; opacity: 0;
to display: block; opacity: 1;
However, in chrome (at least) an object that has display: none
does not animate. The element goes to the end state immediately.
My work around for this is to first set the element to display: block; opacity: 0;
and then do the transition in the next frame (using requestAnimationFrame()
. It is kind of awkward, and I can't find any explanation for this behavior in the spec. I know that I could use the visibility
-attribute, but I don't want to use it because I don't want to layout the hidden element.
So, the questions are: Is this the correct behavior or a bug? If it is the correct behavior, is there a better way to write the code? Note that I'm not asking if there are any libraries that can do it, I want to know if there is a better way to do it directly on the DOM.