设置图像无裁剪和拉伸 [英] Setting image without cropping and stretching
问题描述
我想在img标签中设置图像,不裁剪或拉伸它。
也就是说,我设置的图像比率是1:1,但图像的宽高比可能不同,因此我既不想改变纵横比,也不想垂直或水平裁剪。我的图片动态变化。
I want to set image in img tag, without cropping it or stretching it. That is, the image ratio I have set is 1:1 but image may vary in aspect ratio, so I neither want to change the aspect ratio nor want to crop it vertically or horizontally. my images are changing dynamically.
我已经检查了多个解决方案,例如:这一个表示裁剪高度或宽度。但我不想两个。
I have checked multiple solutions for eg: This one which suggests either crop height or width. But I don't want both.
目前我在这里:
HTML:
Currently I am at this: HTML:
<div id="container">
<img id="imgHolder" />
</div>
和CSS
#container{
height: 100px;
width: 100px;
background-color: yellow;
overflow: hidden;
}
#imgHolder{
height: 100%;
/* OR width: 100%; */
}
帮助。我只喜欢CSS。
Help. I prefer CSS only.
推荐答案
你可以只设置 max-width
和您的图片的 max-height
you can just set both the max-width
and the max-height
of your images
#container img {
max-width: 100%;
max-height: 100%;
}
这样做,图像不会被拉伸,因为你不改变它的 width
或 height
:无论图像大小如何,一起设置上述属性可确保最长边缩减到最大宽度(或高度)的父 div
,而另一个可以自由适应自己,保持原始的图像比率。
Doing so the image won't be stretched since your not changing its width
or height
: whatever is the image size, setting the above properties together ensures that the longest side is reduced to the maximum width (or height) of its parent div
, while the other one can freely adapt itself, keeping the original image ratio.
示例 http://codepen.io/anon / pen / qEjLZa
中心图像(包括ver。和hor。)的示例: http://codepen.io/anon/pen/NPgege
Example with centered images (both ver. and hor.): http://codepen.io/anon/pen/NPgege
这篇关于设置图像无裁剪和拉伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!