For some time I have been looking for a way to animate the way that dynamically filled elements expand and contract in my layouts, but without giving them explicit heights or widths. I like the idea of using the flexibility of websites to display information as best fits the user's (and device's/browser's) needs. If I can I like to let content flow and determine at least the height of itself. This pop's up for me fairly often when building accordion or dropdown navigation elements. Most of the time I don't know exactly what is going to be inside of them when writing the module code to display it.

Then I stumbled across this post: How to animate height from 0 to auto using CSS Transitions

It's a really short post, but for anyone who refuses to click on links here is the code Brad Shaw suggests. The key is transitioning max-height from 0 to something greater.

  .our_content {
    /* Initially we don't want any height, and we want the contents to be hidden */
    max-height: 0;
    overflow: hidden;

    /* Set our transitions up. */
    -webkit-transition: max-height 0.8s;
    -moz-transition: max-height 0.8s;
    transition: max-height 0.8s;
}
.outside_box:hover .our_content {
    /* On hover, set the max-height to something large. In this case there's an obvious limit. */
    max-height: 200px;
}

I took this information and threw together a little pen to test it out.

As you can see, the content area is blended in and out vertically. It is not the most beautiful animation to grace the internet, but it seems to achieve what I want. There are, however, some caveats to it's implementation.

  1. Using max-height:0 -> infinity is pretty clever, but the upper bound still needs to be set to a concrete value. In my example I use 200rem. This may or may not be enough to display all of the information.

  2. Also the transition seems to cover the entire area that max-height could display, so the animation will seem to be delayed either on toggle on or off, until the visible portion of the block is reached.

All in all this seems like a solution with some potential. I hope to put in some more time and round it out where possible. I am amused by the hacky checkbox as hidden control with some great *, ~ and attribute selectors css code, and if you are interested you can have a good laugh at it in the pen.


2,450 4 11