不定宽高元素的水平垂直居中方法及兼容性
<!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 |
Modern & IE8+ |
Yes |
Scroll, can overflow container |
Yes |
Yes* |
Variable Height not perfect cross-browser |
|
All |
No |
Scroll |
Resizes but doesn't stay centered |
No |
Not responsive, margins must be calculated manually |
|
Modern & IE9+ |
Yes |
Scroll, can overflow container |
Yes |
Yes |
Blurry rendering |
|
Modern & IE8+ |
Yes |
Expands container |
No |
Yes |
Extra markup |
|
Modern, IE8+ & IE7* |
Yes |
Expands container |
No |
Yes |
Requires container, hacky styles |
|
Modern & IE10+ |
Yes |
Scroll, can overflow container |
Yes |
Yes |
Requires container, vendor prefixes |
如果有哪里写的不对希望可以跟我说一下,非常感谢
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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代理技术深度解析与实战指南