0

How can I make a hidden element unhidden and transition?

Example:

I want to animate a <div> that has display: none; height: 0px; transition: height 600ms;.

So on click I add a class with display: block; height: 100px;.

The height does not animate.

CodePen

I would prefer a solution that uses transition, but if none is available I can use animation. I am not looking for any answers that use javascript.

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
Don P
  • 60,113
  • 114
  • 300
  • 432
  • Duplicate: http://stackoverflow.com/questions/3331353/transitions-on-the-display-property You can't animate with display. Use visibility and/or opacity. – Fantasterei Oct 10 '16 at 19:38
  • Isn't this a drawback in CSS? http://stackoverflow.com/questions/3331353/transitions-on-the-display-property – m4n0 Oct 10 '16 at 19:39
  • @Jabaluza - yes I know display isn't animatable, but the other properties are. So is the answer that you can't transition ANY property if a singly changed one isn't supported? – Don P Oct 10 '16 at 19:41
  • @DonnyP yeah, you can't animate every property. – Fantasterei Oct 10 '16 at 19:46

1 Answers1

7

You're not going to be able to animate it with display. If you give your .submenu class an overflow: hidden; and remove the display: none;, it will animate as desired since you're already animating the height from 0.

CSS

.submenu {
  height: 0;
  overflow: hidden;  /* <-- Add This */
  background: blue;
  transition: height 600ms ease 0ms;
}

CodePen

$('.menu').click(function(){
  $('.submenu').toggleClass('open');        
});
.menu {
  background: red;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  transition: all .2s ease-in-out;
}

.submenu {
  height: 0;
  overflow: hidden;
  background: blue;
  transition: height 600ms ease 0ms;
}
.submenu.open {
  display: block;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <h1>Click me to expand a submenu</h1>
  <div class="submenu">  
    <p>test 1</p>
    <p>test 2</p>
  </div>
</div>
Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
  • Beautiful solution! Is there a way to dynamically set the height? When I put height: auto(or inherit, fit-content, initial, parent, etc), it breaks the animation. Is there a way to set it to fit-content and still get the animation? – Kris Bonev Apr 10 '18 at 15:15
  • 1
    @KrisBonev in order for it to animate properly, there needs to be a defined height (or even width). Let's say you have a div that has a dynamic height (set to auto), and you want to animate it to a height of 300px. All the browser will see is that you want to go to 300px, but it won't know where to animate it **from**. That's why when you animate with CSS, you have to specify a starting point for the animation. – Hunter Turner Apr 10 '18 at 15:21