CSS:当没有固定大小的div时,垂直对齐div [英] CSS: Vertically align div when no fixed size of the div is known
问题描述
如何将包含图像(或Flash)的< div>
与CSS垂直对齐。高度和宽度是动态的。
How do I align a <div>
which contains an image (or flash) vertically with CSS. Height and width are dynamic.
推荐答案
这是一个纯CSS2解决方案, 。不涉及任何黑客。我发现它这个答案,我也演示了它在此答案。
This is a pure CSS2 solution for horizontally and vertically centering without known sizes of either container nor child. No hacks are involved. I discovered it for this answer and I also demonstrated it in this answer.
解决方案基于 vertical-align:middle
结合 line-height:0
,其父级具有固定的行高。
The solution is based on vertical-align: middle
in conjunction with line-height: 0
, which parent has a fixed line-height.
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;
}
$ b < FF 6.0,Chrome 13.0。
Tested on Win7 in IE8, IE9, Opera 11.51, Safari 5.0.5, FF 6.0, Chrome 13.0.
唯一需要注意的是IE7,两个最内层的元素必须在一行中声明, in this fiddle :
The only caveat is IE7, for which the two innermost elements have to declared at one line, as demonstrated in this fiddle:
<span id="center">
<span id="wrap"><img src="http://lorempixum.com/300/250/abstract" alt="" /></span>
</span>
请注意,IE7也需要span。在每个其他浏览器中,跨度可以是div的。
Note that the span's are also required for IE7. In every other browser, the span's may be div's.
这篇关于CSS:当没有固定大小的div时,垂直对齐div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!