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

<!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;
width: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;
width:400px;
height:400px;
}
#imgbox{
display: inline-block;
}
*/
/*方法三:*/
/*#divbox{
border: 2px solid #000000;
position: relative;
width: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;
width: 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

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

posted @   不再犯错  阅读(135)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示