Warm tip: This article is reproduced from serverfault.com, please click

CSS transition of height for injected content into a DIV

发布于 2014-08-14 15:41:01

I'm having a following template:

<div class='content'>
    {{content}}
</div>

And following style:

.content {
  margin-top: 30px;
  background-color: skyblue;
  width: 300px;
  transition: all linear 0.5s;
}

Please note that {{content}} will grow or shrink (technically to extend a card to show more information or hide it). I've already set the css transition and it does work when manually setting a different height to the element. However when more content is injected into content no transition is made, just a plain old resizing. Any help of getting the transision right?

See following plunkr

Thanks,

Amit.

Questioner
amit
Viewed
1
jcaron 2014-08-15 00:08:05

I believe that's quite normal, transitions apply only to changes to the CSS, not for computed changes.

One option might be to have a nested div, set overflow: hidden on the outer one, then get the computed height of the inner one and set it on the outer one to get the transition.

CSS:

#outer {
    margin-top: 30px;
    background-color: skyblue;
    width: 300px;
    transition: all linear 0.5s;
    overflow: hidden;
}

HTML:

<button id="more" onclick="increase();">More</button>
<button id="more" onclick="decrease();">Less</button>
<div id="outer">
    <div id="inner">
        lorem ipsum
    </div>
</div>

JS:

function increase()
{
    var o = document.getElementById('inner');
    var t = o.innerHTML;
    for (var i=0 ; i<20;i++)
        t += " lorem ipsum";
    o.innerHTML = t;
    adjustHeight();
}

function decrease()
{
    var o = document.getElementById('inner');
    o.innerHTML = "lorem ipsum";
    adjustHeight();
}

function adjustHeight()
{
    var i = document.getElementById('inner');
    var o = document.getElementById('outer');

    o.style.height = window.getComputedStyle(i).height;
}

Working fiddle: http://jsfiddle.net/Lnts7w1f/