Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate height based on children's height

I have a container — imagine that it contains pages in an app. I’m using animate.css to slide from a page to another. Pages have different heights (according to their content), so the container has to resize to accommodate.

I can’t for the life of me get the height to animate!

The CodePen (and the following code) demonstrate a working sliding animation between pages but the container's height just changes instantly.

http://codepen.io/anon/pen/jqbExY

HTML:

<button id=btn>animate</button>
<main>
  <section class="first">Little content</section>
  <section class="second">Lots of content ........</section>
</main>

CSS:

button {
  display: block;
  margin: auto;
}

main {
  border: 1px solid black;
  width: 400px;
  margin: auto;
  min-height: 100px;
  height: auto;
  transition: height 1s linear;
}

.first {
  background-color: red;
}

.second {
  background-color: green;
  display: none;
}

.leave {
  position: absolute;
}

JavaScript (jQuery just for demonstration, in reality I'm using Angular):

$('#btn').on('click', function() {
  var $first = $('.first');

  $first.addClass('slideOutLeft animated leave').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
    function(e) {
      $first.hide();
    });
  $('.second').addClass('slideInRight animated').show();
});
like image 551
gberger Avatar asked Aug 31 '25 02:08

gberger


1 Answers

Rather than trying to animate the height of the container, you should animate the height of the element within it. As a basic example, you could do something like:

Codepen Update

CSS

.second {
  background-color: green;
  max-height: 0px; // Use max-height so you can animate without setting a fixed height
  transition: 2s;
  overflow: hidden; // Instead of display: none;
}
.height {
  max-height: 200px; // Height is dynamic up to 200px
}

JQuery

$('.second').show().addClass('slideInRight animated height');
like image 86
Derek Story Avatar answered Sep 02 '25 16:09

Derek Story