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

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


当前回答

试试这个:

div.container {
    max-width: 200px;//real picture size
    max-height: 100px;
}

/* resize images */
div.container img {
    width: 100%;
    height: auto;
}

其他回答

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">

你可以使用对象匹配属性:

.my-image {
    width: 100px;
    height: 100px;
    object-fit: contain;
}

这将适合图像,而不改变比例。

css属性max-width和max-height工作得很好,但IE6和IE7不支持。你会想要在高度/宽度上使用这个,这样你就不会意外地缩放图像。你只需要按比例限制最大高度/宽度。

Try

transform: scale(0.5, 0.5);
-ms-transform: scale(0.5, 0.5);
-webkit-transform: scale(0.5, 0.5);

通过保持图像的纵横比来缩放图像

试试这个,

img {
  max-width:100%;
  height:auto;
}