html - 使用最大高度、宽度自动限制 div 中的 img

标签 html css image

这段简单的代码在 WebKit 浏览器中运行良好,但在 IE 和 Firefox 中却失败了。我需要将 img 标签用于其他功能,因此 background-image 不是一个选项。

片段

img {
  max-width: 100%;
  height: auto;
}
.vgp-dtable {
  width: 100%;
  max-width: 860px;
  margin: 0 auto 1em;
  display: table;
}
.vgp-dtable .row {
  display: table-row;
}
.vgp-dtable .row .art,
.vgp-dtable .row .txt {
  display: table-cell;
  vertical-align: top;
}
.vgp-dtable .row .art {
  width: 30%;
  text-align: right;
}
.vgp-dtable .row .art img {
  width: auto;
  max-height: 280px;
}
.vgp-dtable .row .txt {
  width: 70%;
  text-align: left;
  padding-left: 8px;
}
<div class="vgp-dtable">
  <div class="row">
    <div class="art">
      <img src="http://vgpavilion.com/mags/1982/12/vg/ads/003-004-005_tn.jpg">
    </div>
    <div class="txt">
      <p>Here's some sample text.</p>
    </div>
  </div>
  <a id="riddle-of-the-sphinx"></a>
  <div class="row">
    <div class="art">
      <img src="http://vgpavilion.com/mags/1982/12/vg/thumbs/007.jpg">
    </div>
    <div class="txt">
      <p>Here's some sample text.</p>
    </div>
  </div>
</div>

在 WebKit 中,图像会适本地调整大小以适应最大 height 为 280px 的 30% 宽的容器 block 。然而,在 Firefox 和 IE 中,只有 max-height 受到尊重,并且图像强制它们的容器宽度超过 30%。

一个简单的例子here .这个简单的例子有一个工作版本,在损坏的 display:table 实现之上使用 float 方法。

可以看到全页here

我尝试了多种容器组合,除非在 Firefox 或 IE 中以绝对值指定,否则图像永远不会遵守 width。在之前的例子中,我使用了 background-image 解决方案,它适用于所有经过测试的浏览器,但我真的不想这样做。我通过使用 float 而不是 display: table-cell 找到了解决方案,但令我困惑的是它使用几乎相同的 table 方法被破坏了在 IE 和 Firefox 中,所以也许有人可以发现我遗漏的东西或我不应该添加的东西。

最佳答案

只需添加 table-layout:fixed这里:

.vgp-dtable {
  width: 100%;
  max-width: 860px;
  margin: 0 auto 1em;
  display: table;
  table-layout: fixed  /*added*/
}

关于html - 使用最大高度、宽度自动限制 div 中的 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35052314/

相关文章:

javascript - 获取文本框的值到另一个html文件

html - 使用 Flexbox 重新定位选择器

css - 背景上带有文本的按钮的反色

html - float 元素的中心未知

swift - 下载前获取放置在远程服务器上的图像的大小

php - 在php中垂直打印.txt文件内容

CSS Transition 仅适用于某些元素

jquery - 有没有办法动画显示:none?

image - CSS 图像集/背景图像。 img srcset 的替代方案?有人用这个吗?

html - CSS Float 导致中间空白