我有一张图片,我想给它设置一个特定的宽度和高度(像素)

但是如果我使用css (width:150px;高度:100px),图像将被拉伸,并且它可能是丑陋的。

如何使用CSS填充图像到特定的大小,而不是拉伸它?

填充和拉伸图像示例:

原始图像:

拉伸图片:

填充图片:

请注意,在上面的填充图像示例中:首先,图像被调整为150x255(保持长宽比),然后,它裁剪为150x100。


当前回答

我觉得现在回答这个问题有点晚了。无论如何,希望这对将来的人们有所帮助。 我面临的问题,定位卡片的角度。有针对事件数组显示的卡片。如果事件的图像宽度对于卡片来说比较大,图像应该从两边裁剪,高度为100%来显示。如果图像高度较长,图像的底部被裁剪,宽度为100%。这是我的纯css解决方案:

HTML:

 <span class="block clear img-card b-b b-light text-center" [ngStyle]="{'background-image' : 'url('+event.image+')'}"></span>

CSS

.img-card {
background-repeat: no-repeat;
background-size: cover;
background-position: 50% 50%;
width: 100%;
overflow: hidden;
}

其他回答

我帮助构建了一个名为Fillmore的jQuery插件,它在支持它的浏览器中处理背景大小:封面,并为那些不支持它的浏览器提供了一个垫片。看看吧!

增强了@afonsoduarte接受的答案。 以防你使用自举


There are three differences:

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标签来做这件事,只需要在元素上设置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/

<div class="container">
     <img src="http://i.stack.imgur.com/2OrtT.jpg"/>
</div>

<style>
.container {
       width: 150px;
       height: 100px;
       overflow: hidden;
}
</style>

这将填充图像到特定的大小,而不拉伸或裁剪它

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;
}