0
<div class="box">
    <div class="pic">
        <img src="/images/img.png" class="img_pic" />
    </div>
</div>

.box {
    border: 1px solid #333;
    cursor: pointer;
    height: 73px;
    margin: 40px 42px 0 0;
    width: 269px;
}
.img_pic {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

我希望图像(“img_pic”)也垂直居中。有了我所拥有的,我可以水平而不是垂直地做到这一点。我试过vertical-align: middle;了,但没用,我试过line-height: 73px了,因为盒子的高度是73px. 我似乎想不出办法解决这个问题。

如何在保持水平居中的同时垂直居中图像?

4

4 回答 4

2

不要使图像成为块元素。作为内联元素,您可以将其作为文本居中。然后将行高设置为与框相同,并将图像上的垂直对齐设置middle为将其放在文本行的中间:

.box {
    border: 1px solid #333;
    cursor: pointer;
    height: 73px;
    margin: 40px 42px 0 0;
    width: 269px;
    text-align: center;
    line-height: 73px;
}
.img_pic {
    vertical-align: middle;
}

演示:http: //jsfiddle.net/AwgNy/

于 2013-09-05T22:16:53.947 回答
1

您不能vertical-align阻止元素。

如果您知道图像的高度,您可以在 `.box.' 上放置一个等于top和或一个等于和填充。bottom margin.img_plctopbottom

正如您所说,它是可变高度,那么您可以使用display: table-cell for .box 与vertical-align: middle;

于 2013-09-05T22:13:49.620 回答
0

如果您知道图像的尺寸,您可以在 css 中执行此操作,并使用边距将其向下推:

margin-top:/*(box height / 2) - (image height / 2)*/;

或使用相对和绝对定位:

.box
{
    position:relative;
    /*other code*/
}

.image_pic
{
    position:absolute;
    top:/*(box height / 2) - (image height / 2)*/;
}

如果您不能保证图像的尺寸,那么您应该使用 javascript/jQuery 来获取图像高度并使用与上述相同的公式来计算偏移量。然后仍然使用 javascript/jQuery,编辑图像的 css 以设置margin-topor的偏移量top

于 2013-09-05T22:25:20.737 回答
0

只需在此处使用此 CSS演示

.box {
    border: 1px solid #333;
    cursor: pointer;
    height: 73px;
    margin: 40px 42px 0 0;
    width: 269px;
    position:relative
}
.img_pic {
    display: block;
    position:absolute;
    top:0px;
    left:0px;
    right:0px;
    bottom:0px;
    margin:auto
}
于 2013-09-09T12:42:55.313 回答