我有一张图片,我想给它设置一个特定的宽度和高度(像素)
但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。
如何使用CSS填充图像到特定的大小,而不是拉伸它?
填充和拉伸图像示例:
原始图像:
拉伸图片:
填充图片:
请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。
我有一张图片,我想给它设置一个特定的宽度和高度(像素)
但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。
如何使用CSS填充图像到特定的大小,而不是拉伸它?
填充和拉伸图像示例:
原始图像:
拉伸图片:
填充图片:
请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。
当前回答
解决方案不需要图像作为背景,将自动调整大小而不被切断或扭曲。
另一种解决方案是将图像放在具有所需宽度和高度的容器中。使用此方法,您不必将图像设置为元素的背景图像。
然后你可以用img标签来做这件事,只需要在元素上设置max-width和max-height。
CSS:
.imgContainer {
display: block;
width: 150px;
height: 100px;
}
.imgContainer img {
max-width: 100%;
max-height: 100%;
}
HTML:
<div class='imgContainer'>
<img src='imagesrc.jpg' />
</div>
现在,当你改变容器的大小时,图像将自动增长到最大,而不会超出边界或扭曲。
如果你想让图像垂直和水平居中,你可以改变容器css为:
.imgContainer {
display: table-cell;
width: 150px;
height: 100px;
text-align: center;
vertical-align: middle;
}
这是一个JS小提琴http://jsfiddle.net/9kUYC/2/
其他回答
解决方案不需要图像作为背景,将自动调整大小而不被切断或扭曲。
另一种解决方案是将图像放在具有所需宽度和高度的容器中。使用此方法,您不必将图像设置为元素的背景图像。
然后你可以用img标签来做这件事,只需要在元素上设置max-width和max-height。
CSS:
.imgContainer {
display: block;
width: 150px;
height: 100px;
}
.imgContainer img {
max-width: 100%;
max-height: 100%;
}
HTML:
<div class='imgContainer'>
<img src='imagesrc.jpg' />
</div>
现在,当你改变容器的大小时,图像将自动增长到最大,而不会超出边界或扭曲。
如果你想让图像垂直和水平居中,你可以改变容器css为:
.imgContainer {
display: table-cell;
width: 150px;
height: 100px;
text-align: center;
vertical-align: middle;
}
这是一个JS小提琴http://jsfiddle.net/9kUYC/2/
增强了@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 ..." />
不使用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%);
}
试试这个:http://jsfiddle.net/D7E3E/4/
使用溢出容器:隐藏
编辑:@多米尼克·格林打败了我。
据我所知,有一个插件可以让这变得简单。
jQuery插件:自动转换<img>为背景样式
<img class="fill" src="image.jpg" alt="Fill Image"></img>
<script>
$("img.fill").img2bg();
</script>
此外,这种方式也满足了可达性需求。因为这个插件不会从你的代码中删除你的<img>标签,屏幕阅读器仍然会告诉你ALT文本,而不是跳过它。