在保持CSS中的宽高比的同时,将图像大小设置为容器? [英] Size image to container while maintaing aspect ratio in CSS?
问题描述
我有一堆不同(未知)尺寸的图片。
我想将这些图片放入一个div,让它们自动符合div,同时保持其长宽比。
换句话说,如果图像宽度大于高,则宽度将为100%,高度将相应缩放。如果图像高于宽,则高度将为100%,宽度将相应地缩放。
在纯CSS中有任何方法吗? p>
感谢
使用css属性 max-width
和 max-height
http://fiddle.jshell.net/sHAQ9/
HTML
< img src =http://dummyimage.com/200x300/000000/ffffff.png&text=tall%20image/>
< / div>
< div>
< img src =http://dummyimage.com/300x200/000000/ffffff.png&text=wide%20image/>
< / div>
CSS
div {
width:150px;
height:150px;
overflow:hidden;
background:#ccc;
margin:10px;
text-align:center;
line-height:150px;
}
div img {
max-width:100%;
max-height:100%;
vertical-align:middle;
}
I have a bunch of images of different (unknown) dimensions.
I want to drop these images into a div and have them automatically conform to the dimensions of the div, while maintaining their aspect ratio.
In other words, if the image is wider than high, the width will be 100%, and the height will scale accordingly. If the image is higher than wide, the height will be 100%, and the width will scale accordingly.
Is there any way to do this in pure css?
Thanks
Using the css properties max-width
and max-height
on the image will get you where you need to be.
Fiddle
http://fiddle.jshell.net/sHAQ9/
HTML
<div>
<img src="http://dummyimage.com/200x300/000000/ffffff.png&text=tall%20image"/>
</div>
<div>
<img src="http://dummyimage.com/300x200/000000/ffffff.png&text=wide%20image"/>
</div>
CSS
div {
width: 150px;
height: 150px;
overflow: hidden;
background: #ccc;
margin: 10px;
text-align: center;
line-height: 150px;
}
div img {
max-width: 100%;
max-height: 100%;
vertical-align: middle;
}
这篇关于在保持CSS中的宽高比的同时,将图像大小设置为容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!