Div垂直对齐图像

时间:2012-08-22 18:42:29

标签: html css

我有一个div图像“image.jpg”。

使用text-align=center,图像水平居中。

然而,它不是垂直对齐的。我如何实现垂直对齐?

<div style="vertical-align: middle;text-align:center;">
    <img title="Title3" src="image.jpg" style="display: inline;" id="idImage">
</div>

3 个答案:

答案 0 :(得分:1)

使用this article中所述的vertical-align属性。请注意,要使vertical-align正常工作,您还需要执行display: table-cell

div.centered {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    /* other styling */
}

我已将<div>的班级名称centered。{/ p>

此外,您不应使用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;
}

答案 1 :(得分:0)

您必须知道此工作的尺寸(如果您有不同的尺寸,则使用javascript获取尺寸)。这也会使图像水平居中(因此您不需要text-align=center

取自css-tricks

.center {
   width: 300px;
   height: 300px;
   position: absolute;
   left: 50%;
   top: 50%; 
   margin-left: -150px;
   margin-top: -150px;
}

高度和宽度是相关图像的高度和宽度,顶部和左边距设置为相应高度和宽度的一半。

答案 2 :(得分:0)

如果设置父容器的高度并设置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;
}

虽然