是否有一种方法来调整(缩小)图像按比例使用CSS?

我用的是JavaScript的方式,只是想看看CSS是否可行。


当前回答

你总是需要这样的东西

html
{
    width: 100%;
    height: 100%;
}

在CSS文件的顶部

其他回答

如果是背景图片,使用background-size:contain。

css例子:

#your-div {
  background: url('image.jpg') no-repeat;
  background-size:contain;
}

2015年回顾:

<img src="http://imageurl" style="width: auto; height: auto;max-width: 120px;max-height: 100px">

我重新访问了它,因为所有常见的浏览器现在都有上面Cherif建议的自动工作,所以它工作得更好,因为你不需要知道图像是否宽于高。

旧版本: 如果你被120x100的盒子限制,你可以这样做

<img src="http://image.url" height="100" style="max-width: 120px">
img{
    max-width:100%;
    object-fit: scale-down;
}

对我有用。它缩小较大的图像以适应方框,但较小的图像保持原始大小。

使用这种简单的缩放技术

img {
    max-width: 100%;
    height: auto;
}
@media {
  img { 
    width: auto; /* for ie 8 */
  }
}

使用CSS按比例调整图像大小:

img.resize {
    width:540px; /* you can use % */
    height: auto;
}