我有一张图片,我想给它设置一个特定的宽度和高度(像素)
但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。
如何使用CSS填充图像到特定的大小,而不是拉伸它?
填充和拉伸图像示例:
原始图像:
拉伸图片:
填充图片:
请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。
我有一张图片,我想给它设置一个特定的宽度和高度(像素)
但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。
如何使用CSS填充图像到特定的大小,而不是拉伸它?
填充和拉伸图像示例:
原始图像:
拉伸图片:
填充图片:
请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。
当前回答
如果您想使用图像作为CSS背景,有一个优雅的解决方案。只需在背景大小CSS3属性中使用cover或include即可。
.container { 宽度:150 px; 身高:100 px; 背景图片:url(“http://i.stack.imgur.com/2OrtT.jpg”); background-size:封面; 平铺方式:不再重演; 背景位置:50% 50%; } < div class = "容器" > < / div >
封面会给你一个放大的图像,包含会给你一个缩小的图像。两者都将保留像素长宽比。
http://jsfiddle.net/uTHqs/(使用封面)
http://jsfiddle.net/HZ2FT/(使用contains)
根据Thomas Fuchs的快速指南,这种方法的优点是对Retina显示器友好。
值得一提的是,浏览器对这两个属性的支持不包括IE6-8。
其他回答
我帮助构建了一个名为Fillmore的jQuery插件,它在支持它的浏览器中处理背景大小:封面,并为那些不支持它的浏览器提供了一个垫片。看看吧!
试试这个:http://jsfiddle.net/D7E3E/4/
使用溢出容器:隐藏
编辑:@多米尼克·格林打败了我。
不使用css背景 只有1个div剪辑它 调整到最小宽度,保持正确的纵横比 从中心裁剪(垂直和水平,你可以调整顶部,左&变换)
如果你使用主题之类的,要小心,他们通常会声明img max-width为100%。你必须一个都不做。测试一下吧!
https://jsfiddle.net/o63u8sh4/
<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
<p>Wrapped:</p>
<div>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>
div{
width:150px;
height:100px;
position:relative;
overflow:hidden;
}
div img{
min-width:100%;
min-height:100%;
height:auto;
position:relative;
top:50%;
left:50%;
transform:translateY(-50%) translateX(-50%);
}
增强了@afonsoduarte接受的答案。 以防你使用自举
Providing width:100% on the style. This is helpful if you are using bootstrap and want the image to stretch all the available width. Specifying the height property is optional, You can remove/keep it as you need .cover { object-fit: cover; width: 100%; /*height: 300px; optional, you can remove it, but in my case it was good */ } By the way, there is NO need to provide the height and width attributes on the image element because they will be overridden by the style. so it is enough to write something like this. <img class="cover" src="url to img ..." />
这将填充图像到特定的大小,而不拉伸或裁剪它
img{
width:150px; //your requirement size
height:100px; //your requirement size
/*Scale down will take the necessary specified space that is 150px x 100px without stretching the image*/
object-fit:scale-down;
}