在不知道CSS高度的情况下垂直对齐?

mik*_*ike 4 html css

我通常会使用绝对定位并将顶部设置为50%,使用负边距 - 顶部(儿童高度的一半)垂直居中.在这种情况下,由于子元素的高度会有所不同,因此无效.

那么有没有办法在div中垂直居中div而不知道孩子的身高?

Tom*_*Tom 5

以下jquery函数垂直居中,假设您正在定位的项目已经是位置绝对位置,而父位置是相对的

$.fn.vAlign = function () {
    return this.each(function () {
        $(this).css('top', '50%').css('margin-top', -Math.ceil($(this).height() / 2) + "px");
    });
};
Run Code Online (Sandbox Code Playgroud)

观看行动 - http://jsfiddle.net/vqbMU/2/

更新:

支持css转换的浏览器的纯CSS解决方案(IE9 +)http://caniuse.com/#search=transform

.align-v {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)


Con*_*nex 0

使用 padding top 、 padding Bottom 使元素垂直居中,带或不带高度定义...