Html 在 css 中使用 % 调整图像大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3797395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:39:24  来源:igfitidea点击:

resize images using % in css

htmlcssimageresize

提问by slexAtrukov

I am trying to create a liquid web layout using % for as many things as i can. I have hit a bump when resizing images.

我正在尝试使用 % 为尽可能多的东西创建一个液体网络布局。调整图像大小时我遇到了问题。

both:

两个都:

<img src="source" style="width: 20%; height: 20%;"/>

and

.wall_picture_block img{
width: 20%; 
height: 20%;
}

don't work properly with the height attribte. They resize the image width to 20% of the container but the height stays relative to the image size.(im trying to make squares)

高度属性不能正常工作。他们将图像宽度调整为容器的 20%,但高度相对于图像大小保持不变。(我正在尝试制作正方形)

回答by offhell

The percentages in heightand widthattributes of an image works with the container it is contained in. So to achieve the fluid effect just trying putting in a container around the img and give image height and width: 100%. and now you should be changing the height and width of the container in percentages. Here's an example

在百分比heightwidth。它包含在这样的图像作品与容器的属性来达到生津的功效只是试图把在周围的IMG的容器,让图像的高度和宽度100%。现在您应该以百分比形式更改容器的高度和宽度。这是一个例子

<div style="width: 500px; height: 100px;">
   <img src="your-image-link-here" style="height: 100%; width: 100%;">
</div>

With this your image will achieve a height and width of 500 * 100.

有了这个,您的图像将达到 500 * 100 的高度和宽度。

UPDATE

更新

<div id="wrapper" style="border: 1px solid red; width: 900px; height: 400px;">
  <div id="imgcontainer" style="width: 100%; height: 50%;">
     <img src="ur-img" style="height: 100%; width: 100%;">
  </div>
</div>

Example with a wrapper and the container with the percentages.

带有包装器和带有百分比的容器的示例。

回答by alexp

If you want the image's width to be a percentage of its container, and for the image to maintain its original aspect ratio, define the width in percentage and set the height to auto:

如果您希望图像的宽度为其容器的百分比,并且图像保持其原始纵横比,请以百分比定义宽度并将高度设置为自动:

.wall_picture_block img{
    width: 20%; 
    height: auto;
}

回答by letronje

You should crop the image. Once you use a % for width or height, I think the browser tries to preserve the aspect ratio, regardless of the value for the other dimension.

您应该裁剪图像。一旦您使用 % 表示宽度或高度,我认为浏览器会尝试保留纵横比,而不管其他维度的值如何。