使用CSS按比例更改图像大小 [英] Changing image sizes proportionally using CSS

查看:57
本文介绍了使用CSS按比例更改图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了几天,以配置我的缩略图库,以便所有图像都显示相同的高度和宽度.但是,当我将CSS代码更改为

I have been trying for a couple of days now to configure my thumbnail gallery so all the images appear the same height and width. However, when I change the CSS code to,

max-height: 150px;
max-width: 200px;
width: 120px;
height: 120px;

我得到的都是相同大小的图像,但是长宽比被拉伸了,破坏了图像.有没有办法调整图像容器的大小,而不是调整图像的大小?请允许我保持宽高比,但仍要调整图像大小.(我不介意是否裁掉一些图像.)

I get images that are all the same size, but the aspect ratio is stretched, ruining the images. Is there not a way to resize the image container and not the image instead? Allowing me to keep the aspect ratio, but resize the image still. (I don’t mind if I cut off some of the image.)

推荐答案

这是CSS调整大小的已知问题.除非所有图像都具有相同的比例,否则您将无法通过CSS做到这一点.

This is a known problem with CSS resizing. Unless all images have the same proportion, you have no way to do this via CSS.

最好的方法是拥有一个容器,并调整图像尺寸之一(始终相同).在我的示例中,我调整了宽度大小.

The best approach would be to have a container, and resize one of the dimensions (always the same) of the images. In my example I resized the width.

如果容器具有指定的尺寸(在我的示例中为宽度),则当告诉图像宽度为100%时,它将使其成为容器的完整宽度.高度为 auto 的图像将使图像的高度与新宽度成比例.

If the container has a specified dimension (in my example the width), when telling the image to have the width at 100%, it will make it the full width of the container. The auto at the height will make the image have the height proportional to the new width.

示例:

HTML:

<div class="container">
    <img src="something.png" />
</div>

<div class="container">
    <img src="something2.png" />
</div>

CSS:

.container {
    width: 200px;
    height: 120px;
}

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

这篇关于使用CSS按比例更改图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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