Can you use CSS3 to transition from height:0 to the variable height of content?
views:
88answers:
1
A:
You can, with a little bit of non-semantic jiggery-pokery. My usual approach is to animate the height of an outer DIV which has a single child which is a style-less DIV used only for measuring the content height.
<style type="text/css">
#grow {
-webkit-transition: height .5s;
height: 0;
overflow: hidden;
outline: 1px solid red;
}
</style>
<script type='text/javascript'>
function growDiv() {
var growDiv = document.getElementById('grow');
if (growDiv.clientHeight) {
growDiv.style.height = 0;
} else {
var wrapper = document.querySelector('.measuringWrapper');
growDiv.style.height = wrapper.clientHeight + "px";
}
}
</script>
<input type="button" onclick="growDiv()" value="grow">
<div id='grow'>
<div class='measuringWrapper'>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
</div>
</div>
One would like to just be able to dispense with the measuringWrapper and just set the DIV's height to auto and have that animate, but that doesn't seem to work (the height gets set, but no animation occurs).
<style type="text/css">
#grow {
-webkit-transition: height .5s;
height: 0;
overflow: hidden;
outline: 1px solid red;
}
</style>
<script type='text/javascript'>
function growDiv() {
var growDiv = document.getElementById('grow');
if (growDiv.clientHeight) {
growDiv.style.height = 0;
} else {
growDiv.style.height = 'auto';
}
}
</script>
<input type="button" onclick="growDiv()" value="grow">
<div id='grow'>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
<div>
The contents of my div.
</div>
</div>
My interpretation is that an explicit height is needed for the animation to run. You can't get an animation on height when either height (the start or end height) is "auto".
jhurshman
2010-06-30 13:32:08