在较小的容器中垂直对齐图像

时间:2012-08-21 15:14:47

标签: html css dom width

我有一个100px×100px的容器。我在其中放了一个我不知道尺寸的图像,除了我将宽度设置为100px的事实。我想在CSS中找到一种方法将这个图像垂直对齐在它的容器中间。我卡住了溢出物:隐藏在容器上,以防止它在广场外显示任何东西。

我在这里找到了关于如何做相反的事情(宽度,而不是高度)。

2 个答案:

答案 0 :(得分:1)

将图像包装在两个模仿html表格的div中。外部div将具有display: table属性,内部将具有display: table-cell属性。您可以将内部div的vertical-align属性设置为顶部,中间或底部。

HTML:

<div class="table">
    <div class="table-cell middle">
        <img src="https://www.google.ca/images/srpr/logo3w.png" alt="" />
    </div>
</div>​

CSS:

.table {
    display: table;
    width: 100px;
    height: 100px;
    border: 1px solid blue;
}
.table-cell {
    display: table-cell;
}
.middle {
    vertical-align: middle;
}
img {
    width: 100%;
    outline: 1px solid red;
}

Here's the fiddle.

答案 1 :(得分:0)

您需要知道图像的高度以垂直对齐它,就像使用此CSS一样:

div {
    position:relative;
    overflow:hidden;
}

div img {
    position:absolute;
    top:50%;
    margin-top:-XXXpx /*(where XXX px is half the height of the image)*/
}
相关问题