[英]Div Vertically aligning an image
我有一個圖像為“ image.jpg”的div。
通過使用text-align=center
,圖像被水平居中。
但是,它不是垂直對齊的。 如何實現垂直對齊?
<div style="vertical-align: middle;text-align:center;">
<img title="Title3" src="image.jpg" style="display: inline;" id="idImage">
</div>
使用vertical-align
,如描述財產這篇文章 。 請注意,為了使vertical-align
正常工作,您還需要display: table-cell
。
div.centered {
display: table-cell;
vertical-align: middle;
text-align: center;
/* other styling */
}
我給您的<div>
類的名稱是centered
。
同樣,您不應該使用text-align
來居中,而是添加margin: 0 auto;
圖像樣式。
編輯
HTML:
<div class="centered">
<img src="..." class="centered-image" />
</div>
CSS:
div.centered {
display: table-cell;
vertical-align: middle;
}
img.centered-image {
margin: 0 auto;
}
您必須知道此功能的尺寸(或如果使用其他尺寸,請使用javascript獲取尺寸)。 這還將使圖像水平居中(因此您不需要text-align=center
)
摘自CSS技巧
.center {
width: 300px;
height: 300px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
高度和寬度是所討論圖像的高度和寬度,上下邊距設置為各自高度和寬度的一半。
如果您設置父容器的高度並設置margin-top: auto
,它應該與我認為的中間對齊。 這適用於水平對齊,但是我還沒有嘗試垂直對齊。 無論如何,這將避免絕對定位
如前所述,您還可以使用javascript查找高度,然后設置邊距,如下所示:
var image = document.getElementById("myImage");
var imgHeight = image.style.height;
image.style.marginTop = -(imgHeight/2);
image.style.top = 50%; //you can probably just set this in css and omit this line
你一定要設置
#myImage{
position: absolute;
}
雖然
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.