【问题标题】:img max-width 100%, overscale img to fill divimg 最大宽度 100%,过度缩放 img 以填充 div
【发布时间】:2014-05-21 01:54:03
【问题描述】:

我在 div 内的 img 上使用 max-width: 100%,以便在调整浏览器窗口时自动缩放图像。

如果 div 的宽度大于 img 的宽度,我有什么方法可以使图像在其初始尺寸上以相同的比例“放大/放大”?

谢谢

【问题讨论】:

  • 如果你把它变成一个元素上的background-image而不是使用img你可以使用background-size:cover

标签: css


【解决方案1】:

其实你不需要max-width: 100%;。只需使用 width: 100%; 代替。示例:

img {
  width: 100%;
}

<img src="http://placekitten.com/500/500?image=9" />

上面的小猫图片会总是放大或缩小到其父级的 100% 宽。


您可以通过媒体查询获得一种条件逻辑。在下面的示例中,我们有一个标题和一个 500 像素宽的图像。图片有max-width: 100%;并且有一个媒体查询说当视口宽度超过 500px 时,图像的 width 应该是其父级宽度的 100%(并使主体背景变为灰色以确定何时应用此媒体查询)。

HTML:

<h1>Pellentesque habitant morbi</h1>
<img src="http://placekitten.com/500/500?image=10" />

CSS:

img {
  max-width: 100%;
}

@media (min-width: 500px) {
  body  {
    background-color: #AAA;
  }  
  img {
      width: 100%;
    }
}

因此,当在宽视口内时,图像与该视口一样宽。


或者,尝试将图像设置为背景图像,然后使用 CSS 的background-size: cover;

#image {
  background: #D84E51 url(http://placekitten.com/800/800?image=10) no-repeat center center;
  background-size: cover;
  min-height: 400px;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    相关资源
    最近更新 更多