可能重複:
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 –