如何对齐 <div>
其中包含带有 CSS 的垂直图像(或 flash)。高度和宽度是动态的。
最佳答案
这是一个纯 CSS2 解决方案,用于水平和垂直居中,而无需知道容器或子项的大小。没有黑客参与。我为 this answer 发现了它,我也在 this answer 中展示了它。
The solution 基于 vertical-align: middle
结合 line-height: 0
,其父级具有固定的行高。
HTML:
<span id="center">
<span id="wrap">
<img src="http://lorempixum.com/300/250/abstract" alt="" />
</span>
</span>
还有 CSS:
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
#center {
position: relative;
display: block;
top: 50%;
margin-top: -1000px;
height: 2000px;
text-align: center;
line-height: 2000px;
}
#wrap {
line-height: 0;
}
#wrap img {
vertical-align: middle;
}
在 Win7 IE8、IE9、Opera 11.51、Safari 5.0.5、FF 6.0、Chrome 13.0 中测试。
唯一需要注意的是 IE7,最里面的两个元素必须在一行中声明,如 in this fiddle 所示:
<span id="center">
<span id="wrap"><img src="http://lorempixum.com/300/250/abstract" alt="" /></span>
</span>
请注意,跨度对于 IE7 也是必需的。在所有其他浏览器中,span 可能是 div。
关于html - CSS:当不知道div的固定大小时垂直对齐div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7206640/