垂直居中 div - 浏览器兼容性

Vertically center a div - Browser Compatibility

假设我有一个高度未知的容器 Div A,里面有一个已知高度 Div B

A                                                    
┌─────────────────────────────────┐  ▲               
│                                 │  │               
│    B                            │  │               
│   ┌─────────────────────────┐   │  │               
│   │▲                        │   │                  
│   ││Known Height            │   │  Unknown Height  
│   │▼                        │   │                  
│   └─────────────────────────┘   │  │               
│                                 │  │               
│                                 │  │               
└─────────────────────────────────┘  ▼               

我想在A中垂直居中B。现在我找到了这两种方法,都使用绝对定位。

技术 1

.B {
    /* height has to be declared or it won't work */
    height: 200px; 
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

在这种情况下,必须声明高度才能使其正常工作。 它也不适用于 windows phone.
参考:http://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/

技巧二

.B {
    /* we have to set width and height */
    height: 120px;
    width: 960px;
    position: absolute;
    margin-top: -60px;      /* half of the .B div height */
    margin-left: -480px;    /* half of the .B div widht */
    top: 50%;
    left: 50%;

}

同样在这种情况下,我们必须知道包含的 B div.
的高度 参考:https://css-tricks.com/centering-in-the-unknown/

这两种技术中哪一种是跨浏览器最兼容的技术?
对于大多数浏览器上的这个问题,确实存在更广泛的解决方案(从 IE8 开始,要求较低)。

你可以试试这个:

.B {
    height: 120px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

示例 1: http://jsfiddle.net/k477zumz/(仅垂直居中)

示例2: http://jsfiddle.net/k477zumz/1/(垂直和水平居中)

还有另外两种方法:

1.在容器上使用伪元素

#container:before {
   content:'';
   display:inline-block;
   vertical-align:middle;
   height:100%;
}

#content {
   display:inline-block;
   vertical-align:middle;
}

此方法应该兼容除了IE8及以下的大部分浏览器:http://caniuse.com/#search=%3Abefore

jsFiddle demo

请注意,在这种情况下,垂直居中的元素需要 display:inline-block

2。使用 display:table-cell;

#container {
   display:table-cell;
   vertical-align:middle;
}

此方法应该与 99.98% 的浏览器兼容:http://caniuse.com/#search=css%20table

jsFiddle demo

如果已知元素 B 的大小,那么使用负边距的绝对定位是更可靠的解决方案。它适用于大多数浏览器。