如何在HTML中垂直居中*注入*div顺利?

Diz*_*zzy 3 css vertical-alignment

我有一个完全居中礼貌的div.现在我将一些内容动态注入到居中的div中.它仍然为中心的课程,但它抽搐成中心位置,它看起来简直是丑陋的.

反正是否使定心平稳?我尝试过设置,transition: all但没有效果.

这是一个小提琴,供参考和快速测试:http://jsfiddle.net/qv8fLu4n/

bow*_*art 5

我建议在页面加载时抓取要缩小的元素的高度,将其设置为元素的高度max-height,然后max-height0px和之间切换属性initial height of element.例如:

var i = document.querySelector(".injected-block");
var maxHeight = i.clientHeight + 'px';
i.style.maxHeight = maxHeight;

document.getElementById("injection-button").onclick = (function () {
    if (i.style.maxHeight === '0px') {
        i.style.maxHeight = maxHeight;
    } else {
        i.style.maxHeight = 0;
    }
});
Run Code Online (Sandbox Code Playgroud)

然后可以用transition: max-height消失的元素处理动画,例如

.injected-block {
    overflow: hidden;
    transition: max-height 0.2s;
}
Run Code Online (Sandbox Code Playgroud)

这是一个JSFiddle

编辑

由于目标是从元素看不见开始,你将不得不诉诸一些hacky东西.这是一个功能,它将采用隐形元素,将其粘贴在屏幕外的div中,然后返回它的高度.

var getHeight = function(el) {
    var hiddenDiv = document.getElementById('hidden');
    var clone = el.cloneNode(true);
    clone.className = '';
    clone.style.width = el.clientWidth + 'px';

    hiddenDiv.appendChild(clone);
    var height = clone.clientHeight + 'px';
    hiddenDiv.removeChild(clone);

    return height;
};
Run Code Online (Sandbox Code Playgroud)

所以你要用它:

var i = document.querySelector(".injected-block");
var maxHeight = getHeight(i);
i.style.maxHeight = 0;
Run Code Online (Sandbox Code Playgroud)

这使用div #invisible.示例CSS(需要根据您的情况进行调整),因为:

#hidden {
    position: fixed;
    top: -1000px;
    left: -1000px;
}
Run Code Online (Sandbox Code Playgroud)

这是另一个JSFiddle.干杯!