[英]How to position image in the center/middle both vertically and horizontally
<div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<img src="bla.jpg">
</div>
我怎樣才能讓圖像從這個盒子的中間開始? (垂直和水平中間)
有幾種方法可以做到這一點,如果它需要在所有瀏覽器(IE7+ 和其他瀏覽器)中工作,您需要做不同的事情才能使其在某些情況下工作。
使用絕對位置。 這僅在您知道圖像的大小時才有效。 在這里你將它設置為position: absolute; left: 50%; top: 50%; margin: -<half height of image> 0 0 -<half width of image>
position: absolute; left: 50%; top: 50%; margin: -<half height of image> 0 0 -<half width of image>
position: absolute; left: 50%; top: 50%; margin: -<half height of image> 0 0 -<half width of image>
。
請參閱此處的示例: http : //jsfiddle.net/JPch8/
使用margin: 0 auto;text-align: center;
和line-height/font-size
。 這有點棘手,因為行高在 IE 中對於像圖像這樣的行內塊元素不起作用。 這就是字體大小的用武之地。基本上,您將圖像容器的行高設置為與容器的高度相同。 這將垂直對齊內聯元素,但在 IE 中,您需要設置字體大小才能使其工作。
請參閱此處的示例: http : //jsfiddle.net/JPch8/2/
在支持display: flex
現代瀏覽器中,您只需將容器 div 設置為display: flex; align-items: center; justify-content: center;
display: flex; align-items: center; justify-content: center;
請參閱此處的示例: https : //jsfiddle.net/ptz9k3th/
將圖像放在帶有text-align:center;
的<div>
text-align:center;
不指定盒子的大小
<div class="picture_div" style="margin:0px auto; text-align:center;">
<img src="media/BezierCurve.gif" />
</div>
或者,您可以指定<div>
框的width
和height
以將圖像(實際上是 div 框)居中。
<div id="blue" style="border:1px solid blue; width:100px; height:100px; margin:10px auto;">
<img src="media/BezierCurve.gif" />
</div>
“ float:left; position:relative
”可能無法按預期工作。 浮動元素被認為是絕對的。
要使圖像垂直居中,您需要在 div 上設置高度,並且需要在其父項上設置高度。 (垂直居中是一種痛苦)。 如果這些是您唯一的元素,我下面的示例將起作用,但請注意容器上的height: 100%
可能會影響布局的其余部分。
<html>
<head><title></title>
<style type="text/css">
html, body {
height: 100%;
}
#photo_leftPanel {
height: 500px; /*guessing*/
width: 604px;
float: left;
}
#photo_leftPanel img {
margin: auto;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="photo_leftPanel">
<img src="bla.jpg" />
</div>
</body>
</html>
適用於現代瀏覽器的解決方案是 flexbox。 Flex 容器可以配置為水平和垂直對齊其項目。
<div style="display: flex; align-items: center; justify-content: center; width: 600px; height: 600px;">
<img src="bla.jpg">
</div>
HTML:
<div id="photo_leftPanel">
<img src="bla.jpg">
</div>
CSS:
div.photo_leftPanel {
position: relative;
}
div.photo_leftPanel > img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
我希望我明白你想要達到的目標。
<div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<center><img src="bla.jpg" style="vertical-align:middle;"></center>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.