The Problem

CSS transitioning height (or width) between a fixed value and the block's auto size currently doesn't work in most (all?) browsers. However CSS Transitions are faster, easier, and cleaner than JS based animation techniques. What is a web designer to do?

<tl;dr>

Simply use JS to detect an element's height when height: auto and then assign it explicity so CSS can calculate it's transition.

</tl;dr>

But That's J(Query)S!!!

True. The whole method does rely on scripting. However the script is not doing ANY of the heavy lifting. It simply assigns a few properties. Unless you know some magical non-standard CSS properties - or plan on embedding a billion checkboxes in your page - you're going to use scripts to assign the open/close class to your blocks anyway. While we're there we might as well set a simple style property that gives CSS the information it needs to perform a smooth transition.

How it Works

In this example a closed block will have a fixed height allowing only the header to be visible. An open block will have height: auto to allow it to take as much vertical space as necessary to hold it's content. At page load a handler is attached to all elements with the class closeable that will toggle the open/close states and when the block is OPEN to set it's height inline style to the value of it's data-height attribute. Since CSS Transitions are perfectly comfortable mixing inline styles with stylesheets the fixed open height is transitioned.

But then how do we know what to set the data-height attribute to? After page load, while we're already assigning the click handler, we quickly force the element's inline height to auto, store off the element's now dynamic height, and toggle it back by removing the inline height. This SHOULD be an imperceptible change, switching and switching back before the screen redraws. At least for me it has been.

Not production Code

I wrote the pen rather quickly as a proof of concept. It's left as an exercise for the reader to:

  • Detect changes in content/styling for the element so that the data-height attribute can be recalculated
  • While gathering heights for the data-height attribute, before setting height: auto first store any existing height property incase the HTML already has an inline value that must be restored
  • Deal with IE - The boxes like to transition open, but not back closed. I THINK this is an order-of-operations problem where the class change is being applied before the styling change, but I haven't felt like debugging.
  • Make it modular - JQuery plugins are awesome. Especially if you can customize what classes to use, etc.

16,142 2 15