我想在div中水平和垂直居中放置圖像。我已經閱讀了很多,但是我找不到任何有關使用percantages這個職位的信息。這是我的html:如何以百分比垂直居中放置圖像
<div id="two"></div>
<div id="three">
<img src="http://www.medicalpracticeinsider.com/sites/default/files/News%20Box_0.jpg" id="img" />
</div>
<div id="four"></div>
這是我的CSS:
*{
text-align: center;
}
#two{
height:30%;
background-color: green;
}
#three{
height:30%;
background-color: red;
}
#four{
height:30%;
background-color: blue;
}
#img{
height: 50%;
width: auto;
}
所以水平,我text-align
居中。我嘗試使用vertically-align: middle;
爲#img
哪些不起作用。然後,我嘗試使用marign
,但是,不確定爲y使用什麼。如果我使用它的圖像的左上角開始在頁面中間:
#three{
position: relative;
height:30%;
background-color: red;
}
#img{
height: 50%;
width: auto;
position: absolute;
height: 80%;
width: auto;
margin: 0 auto;
}
但似乎沒有任何工作。我究竟做錯了什麼?
謝謝!
我知道,jsfiddle沒有工作,當我嘗試任一。謝謝你的作品!但有一個問題,爲什麼用硬編碼的px填充? – Tom
好嗎?因爲這是一個例子,我們正在嘗試靜態CSS代碼?你也可以通過JavaScript動態地做到這一點,就像這樣; document.getElementById(「#img」)。style.padding =「50px」; –
ah kk nvm我認爲這是一個愚蠢的問題,我認爲everyhting必須在% – Tom