可能重复:
Center an Image vertically and horizontally? css垂直居中图像中的div标签
我怎么会去div标签中设置图像我必须要在正中央?
我只能找到指导text-align:center;
,并将其放置在中间,但不调整垂直高度。
可能重复:
Center an Image vertically and horizontally? css垂直居中图像中的div标签
我怎么会去div标签中设置图像我必须要在正中央?
我只能找到指导text-align:center;
,并将其放置在中间,但不调整垂直高度。
假设你知道图像的高度,用top: 50%
绝对定位它,并将图像高度的一半作为上边距。因此,对于100x100图像:
div.imgContainer
{
position: relative;
}
div.imgContainer > img
{
position: absolute;
top: 50%;
margin-top: -50px;
left: 50%;
margin-left: -50px;
}
动态垂直居中有两个选项。
display: table
和百分比来使它正确对齐,如this article所示。我也有一些运气line-height
和vertical-align
,但那不是动态的。
有一招用的line-height这样做:
<div style="
height: /*div height in px here */ px;
line-height: /*div height in px here */ px;
text-align:center;">
<img src="URL" style="vertical-align:middle;" />
</div>
位置为中心长期以来一直是CSS的问题。以上所有建议均有效,但其中每一个都有一点点黑客感觉。如果你不需要支持IE或者Opera,开始使用HTML5灵活盒模型这是真棒:http://www.html5rocks.com/en/tutorials/flexbox/quick/
.centerbox {
/* basic styling */
width: 350px;
height: 95px;
font-size: 14px;
border: 1px solid #555;
background : #CFC;
/* flexbox, por favor */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
-webkit-box-align: center;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: center;
-moz-box-align: center;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
只要搜索就这样,这个问题是问了很多。 http://stackoverflow.com/questions/2478434/center-an-image-vertically-and-horizontally-css –