不定宽高元素的水平垂直居中方法及兼容性

<!DOCTYPE html>
<html>
<meta name=" " content=" " charset="utf-8"/>
<head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
/*方法一*/
/*#divbox{
border: 2px solid #000000;
position: relative;
400px;
height:400px;
}
#imgbox{
position: absolute;
top: 50%; left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}*/
/*方法二:*/
/*#divbox{
display:table-cell; 
vertical-align:middle;
text-align: center;
border: 2px solid #000000;
position: relative;
400px;
height:400px;
}
#imgbox{
display: inline-block;
}
*/
/*方法三:*/
/*#divbox{
border: 2px solid #000000;
position: relative;
400px;
height:400px;
}
#imgbox{
position: absolute;
margin: auto;
top: 0;
right: 0;
left:0;
bottom: 0;
}*/
/*方法四*/
/*利用弹性布局模型*/
/*#divbox{
border:1px solid #000000;
display: flex;
justify-content: center;
align-items: center;
400px;
height: 400px;
background: #009f95;
}*/

</style>
</head>
<body>
<div id="divbox">
<img src="img/img/mm10.jpg" id="imgbox"/>
</div>
</body>
</html>

对比表格:

这个对照表有助于你根据自己的需求做出正确的选择。

Technique

Browser Support

Responsive

Overflow

resize:both

Variable Height

Major Caveats

Absolute Centering

Modern & IE8+

Yes

Scroll, can overflow container

Yes

Yes*

Variable Height not perfect cross-browser

Negative Margins

All

No

Scroll

Resizes but doesn't stay centered

No

Not responsive, margins must be calculated manually

Transforms

Modern & IE9+

Yes

Scroll, can overflow container

Yes

Yes

Blurry rendering

Table-Cell

Modern & IE8+

Yes

Expands container

No

Yes

Extra markup

Inline-Block

Modern, IE8+ & IE7*

Yes

Expands container

No

Yes

Requires container, hacky styles

Flexbox

Modern & IE10+

Yes

Scroll, can overflow container

Yes

Yes

Requires container, vendor prefixes

如果有哪里写的不对希望可以跟我说一下,非常感谢

原文地址:https://www.cnblogs.com/luoguixin/p/6125631.html