【问题标题】:Vertically center image with 100% width in li with fixed dimensions以 li 为单位,以 100% 宽度垂直居中,尺寸固定
【发布时间】:2014-11-10 11:12:52
【问题描述】:

我正在尝试将放置在固定宽度和高度 li 中的图像垂直居中。 我的基本 HTML 是:

<ul class="list">
    <li class="list-item">
        <div>
            <img src="http://lorempixel.com/400/200" />
        </div>
    </li>
    <li class="list-item">
        <div>
            <img src="http://lorempixel.com/400/200" />
        </div>
    </li>
    <li class="list-item">
        <div>
            <img src="http://lorempixel.com/400/200" />
        </div>
    </li>
    <li class="list-item">
        <div>
            <img src="http://lorempixel.com/400/200" />
        </div>
    </li>
</ul>

我的基本 CSS 是:

.list-item {
    float: left;
    list-style: none;
    width: 200px;
    height: 80px;
    box-sizing: border-box;
    padding: 10px;
    background-color: #63A578;
}

.list-item div {
    overflow: hidden;
    text-align: center;
    height: 80px;
    width: 100%;
    line-height: 80px;
    border: 1px solid red;
}

.list-item img {
    height: auto;
    width: 100%;
    vertical-align: middle;
}

我尝试了this 答案(以及许多其他答案)的变体,直到容器变得小于图像高度为止。然后它停止垂直对齐并溢出它的容器(jsfiddle 这里)。

所以基本上我希望在小于图像高度的固定高度容器中垂直对齐 100% 宽度的 img 而不溢出。有什么想法吗?

【问题讨论】:

    标签: html css


    【解决方案1】:

    在图片中添加display: table-cell。

    http://jsfiddle.net/d8zd7cyt/18/

    更新:http://jsfiddle.net/d8zd7cyt/21/

    【讨论】:

    • 如果您将图像尺寸从 400x200 切换到 200x400(即高度大于宽度),它仍然会溢出。有没有通用的解决方案?
    • 我对 CSS 进行了一些更改,以简化一点,并希望实现您的目标。
    • 虽然更新确实修复了溢出问题,但它并没有在 li 中垂直居中,而是从左上角开始正常显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2015-08-09
    • 2011-03-10
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    相关资源
    最近更新 更多