【问题标题】:Resize an image dynamically with CSS inside a table-cell div在表格单元格 div 中使用 CSS 动态调整图像大小
【发布时间】:2015-06-06 10:15:52
【问题描述】:

我正在尝试创建两列等宽,左侧包含文本,右侧包含图像。如果图像宽度大于列宽,我希望图像缩小到列的宽度,但如果图像小于列宽,我希望图像保持其原始大小。我已经尝试过this question 中的说明,但是如果图像更大,它将占用它需要的任何空间,挤压左侧包含文本的列。我想知道这是否与“table-cell” div 的行为方式有关,或者是否是浏览器在文本之前容纳图像的优先问题。我的代码如下所示:

<div style="display: table; width:100%;">
    <div style="display: table-row;">
        <div style="display: table-cell; width: 50%; vertical-align: middle;">
            <h1>Header</h1>
            <p>Description</p>
        </div>
        <div style="display: table-cell; width: 50%; vertical-align: middle;">
            <img style="max-width: 100%;height:auto;" src="image.jpg">
        </div>
    </div>
</div>

另外,我使用 FireFox 作为我的浏览器进行测试。谢谢!

编辑:我还尝试了另一种方法来使用浮动 div 获得相同的效果(下面的代码)。问题是我希望两列居中,并且我无法将较小的浮动 div 调整为父容器中的全高,因此内部内容是顶部对齐的。但是,图像确实可以正确调整大小,这支持了我的预感,即这个问题与“table-cell” div 的行为方式有关。

<div style="position: relative;">
    <div style="float: left; width: 50%;height:100%;background-color:#F00;">
        <div style="display: table;height:100%;width:100%;">
            <div style="display: table-row;height:100%;width:100%;">
                <div style="display: table-cell;height:100%;width:100%;vertical-align:middle;">
                    <p>content</p>
                </div>
            </div>
        </div>
    </div>
    <div style="float: left; width: 50%;height:100%;background-color:#F00;">
        <div style="display: table;height:100%;width:100%;">
            <div style="display: table-row;height:100%;width:100%;">
                <div style="display: table-cell;height:100%;width:100%;vertical-align:middle;">
                    <img style="max-width:100%;height:auto;" src="image.jpg">
                </div>
            </div>
        </div>
    </div>
</div>

【问题讨论】:

    标签: css image browser resize window


    【解决方案1】:

    代码在 Chrome 中运行良好。根据本文,这似乎仅在 Firefox 中是一个问题: http://www.carsonshold.com/2014/07/css-display-table-cell-child-width-bug-in-firefox-and-ie/

    table-layout:fixed; 添加到样式为 display:table; 的 div 中会得到您正在寻找的结果 - 允许图像最大宽度工作并尊重单元格宽度。

    <div style="display: table; width:100%; table-layout: fixed">
      <div style="display: table-row;">
        <div style="display: table-cell; width: 50%; vertical-align: middle;">
          <h1>Header</h1>
          <p>Description</p>
        </div>
        <div style="display: table-cell; width: 50%; vertical-align: middle;">
          <img style="max-width: 100%;height:auto;" src="image.png">
        </div>
      </div>
    </div>
    

    【讨论】:

    • 抱歉回复延迟,我没​​有意识到有人已经回答了这个问题,但是这个问题仍然困扰着我——这太完美了,谢谢!
    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多