0

I'm trying to create a simple menu with transition. When you click the menu item, it should open with a CSS transition but I'm guessing I'm missing something. My CSS classes are:

.container {
    height: 0;
    overflow: hidden;
    transition: all 0.3s;
    -webkit-transition: all 0.6s;
}

.container div {
    font-size: 13px;
    padding: 5px;
}

.ShowSubMenu {
    height: initial !important;
}

The ShowSubMenu is applied only when clicking the outer menu item. Please check a working example here: http://jsfiddle.net/CwmTZ/

If you switch the height property of the ShowSubMenu to a constant number, the transition will work nicely. The thing is, I don't know how many sub menu items I will have, it must be dynamic.

Thanks!

Shai
  • 77
  • 1
  • 7

2 Answers2

1

This value: height: initial !important; is not animatetable with CSS. You can only transition numeric values.

You can solve it like this:

.container {
    max-height: 0;
    overflow: hidden;
    transition: all 0.3s;
    -webkit-transition: all 0.6s;
}

.ShowSubMenu {
    background: #f00;
    max-height: 200px; /* Something bigger than menu */
    height: initial;
}

Fiddle

Community
  • 1
  • 1
Jonathan
  • 8,771
  • 4
  • 41
  • 78
  • This seems to work well but it looks like the transition is not smooth and affected by the max-height value (try changing 200px to 1000px). Any suggestions? – Shai Jul 23 '14 at 11:51
  • Haven't seen any solution that wasn't a hack. Maybe best bet is to calc the height with JS... – Jonathan Jul 23 '14 at 11:59
0

I create a function to calculate total height of your container element.

js

$(function() {
    $('.Menu').on('click',function() { 
        if ($('.container').hasClass('ShowSubMenu'))
            $('.container').height(findHeight());
        else
            $('.container').height(findHeight());
    });
});

function findHeight(){
    var sumHeight = 0;
     $('.container').children().each(
         function(){
             sumHeight += $(this).outerHeight();
         });
    return sumHeight;
}

fiddle

And an example with more items in menu:

fiddle

Alex Char
  • 32,879
  • 9
  • 49
  • 70