使用HTML / CSS中的最小宽度/高度缩放HTML图片 [英] Scaling images in HTML with a minimum width/height in HTML/CSS only

查看:772
本文介绍了使用HTML / CSS中的最小宽度/高度缩放HTML图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在一个页面中显示一堆图片。图像是不同的大小,一些非常宽,一些非常薄。我想把它们放在固定宽度和固定高度的容器中。

I have to display a bunch of images in a page. Images are of different size, some very wide and some very thin. I want to put them all in a container of fixed width and fixed height.

放置图像的逻辑应该是这样:
说如果图像是小于容器,将其放大到最大尺寸,使得保持纵横比,并将其放置在容器的中心。
如果图像较大,请缩小比例,同时保持宽高比。

The logic of placing the images should be like this: Say if image is smaller than the container, scale it up to the maximum size such that the aspect ratio is maintained, and put it at the center of container. If image is bigger, scale it down while maintaining the aspect ratio.

一些示例:
说我们的容器是150x150,图片大小为100x50。在这种情况下,图像应该放大到150x75。
如果我们有一个大小为100x300的图片,图片应缩小到50x150。

Some examples: Say our container is 150x150, and we have an image sized 100x50. In this case the image should be scaled up to 150x75. If we have an image sized 100x300, the image should be scaled down to 50x150.

虽然这可以很容易地使用javascript,我想如果可能,避免。
我想知道是否有任何方法来实现这一点与CSS。我可以生活在一个CSS3唯一的解决方案,甚至与webkit / firefox特定的指令,只要它工作在最新版本的Chrome,Firefox和Safari(如果没有选择,我会使用IE的后备)。

While this can be easily done with javascript, I'd like to avoid that if possible. I'm wondering if there's any way to accomplish this with CSS alone. I can live with a CSS3 only solution, or even with webkit/firefox specific directives, as long as it works on latest versions of Chrome, Firefox and Safari (I will use a fallback for IE if there's no choice).

编辑:我当然知道max-height和max-width。问题是,如果我将max-height和max-width都设置为150,则图片将不会按比例放大。

I know about max-height and max-width of course. The issue is that if I set both max-height and max-width to 150, images won't be scaled up if needed.

推荐答案

不要使用< img> 。而应使用 background-image 样式:

Don't use an <img>. Instead, use a background-image style:

background: transparent url('path/to/image.png') no-repeat scroll center center;
background-size: contain;

background-size 缩放图像上下,以便它紧贴在容器内。

The background-size does the magic, scaling the image up or down so that it snugly fits inside the container.

这篇关于使用HTML / CSS中的最小宽度/高度缩放HTML图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆