24

please see the following jsFiddle

http://jsfiddle.net/SgyEW/10/

You can click the various buttons which shows different length content which causes the box to grow/shrink.

I want the height change to be animated so it is not so jumpy, I tried this by adding:

-webkit-transition: all 1s linear;

But that has no effect in this use case. Any ideas in terms of a solution that doesn't require JavaScript?

Thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
TheExit
  • 5,220
  • 12
  • 37
  • 49

2 Answers2

8

I'm afraid there is no way of animating height with CSS3 transitions without some Javascript assistance, check out:

How can I transition height: 0; to height: auto; using CSS?

Can you use CSS3 to transition from height:0 to the variable height of content?

Additionally, your code goes from display: none to display: block, which wouldn't have an effect on height in any case. Instead of display none use height: 0 with overflow: hidden;

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
methodofaction
  • 70,885
  • 21
  • 151
  • 164
2

It has been 8 years, but for those who look for the solution to this request:

JS Fiddle

CSS

#box {
border: 1px solid gray;
background-color: #f3f3f3;
-webkit-transition: all 1s linear;
}

.content {display:none}

.new_content {
  transition: 1s;
}

JS

$('.toggler').on('click', function() {

var idname = $(this).attr('name');
var content = $('#' + idname).html();
var content_height = $('#' + idname).height();
$('.new_content').html(content).css("height", content_height);

});

Also, what has been changed:

  • You don't use anymore "display: none" and "display: block" as the method you are based on. You prefer to use content replacement of a static shown div
  • The content div ('.new_content') doesn't have a height, its optional.
  • The JS sets the height based on the hidden div.
  • The transition does the job.

Hope it helps.

MaciejLisCK
  • 3,706
  • 5
  • 32
  • 39
YArea
  • 29
  • 1
  • 2
    Actually this not really what was asked for … this doesn't dynamically animate the height but rather setting it directly. If the contents height changes without triggering the height recalculation (in this example simply by an window resize) this fails. It would be possible to use a variety of triggers to fetch most cases but then it would be not really performant i guess … – GDY Nov 04 '19 at 15:09