Transitioning accordions from small height to full height with CSS

Posted by arkanciscan on Stack Overflow See other posts from Stack Overflow or by arkanciscan
Published on 2012-12-02T04:56:41Z Indexed on 2012/12/02 5:03 UTC
Read the original article Hit count: 413

Filed under:
|
|

I am building an accordion list and I want it to animate open and closed using a CSS -webkit-transition:. The animation is triggered by an event handler that simply toggles the .open class on and off. The problem is that when I click it, the animation goes from closed height to 0px height then jerks back to full height instead of smoothly animating to full height.

HTML

<ul class="accordion">
    <li>Foo
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc quis leo sit amet justo vulputate volutpat. Suspendisse potenti. Aliquam aliquet justo ut turpis suscipit adipiscing.</p>
    </li>
    <li class="open">Baz
        <p>Ut velit magna, sagittis at blandit accumsan, vestibulum et dolor. Aliquam elit ante, congue vel pharetra ut, ultricies non est. In hac habitasse platea dictumst. Donec velit ligula, sodales a imperdiet non, sagittis id mauris.</p>
    </li>
    <li>Bar
        <p>Cras sit amet gravida lacus. Nulla consequat molestie nunc nec fermentum. Donec lobortis pretium quam sit amet scelerisque.</p>
    </li>
</ul>?

Javascript

$('.accordion').delegate('li', 'click', function(li){
    $(this).toggleClass('open');
});

Css

.accordion li.open{
    -webkit-transition: height 1s;
}

.accordion li:not(.open){
    height: 1em;
    -webkit-transition: height 1s;
}
?

Try it on JSFiddle and see what I mean.

I've already figured out how to make it work, but it requires setting an explicit height on the .open class. The accordions have variable height however, and creating an explicit selector for each one is obtrusive and unmaintainable. Can anyone give me a better solution than this?

Here it is working with an explicit height that doesn't fit the content

© Stack Overflow or respective owner

Related posts about css

Related posts about css3