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

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

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

填充和拉伸图像示例:

原始图像:

拉伸图片:

填充图片:

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


当前回答

你必须在CSS中使用background-size: cover

JS代码

 <div>
   <div className={styles.banner}>banner</div>
 </div>

css代码

.banner{
  background: 
    url("./images/home-bg.jpg");
  background-size: cover;
  height: 53rem;
  width: 100%;
}

对象匹配不工作 Background-size: contains也不工作

其他回答

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

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

在阅读StackOverflow的答案后,我得到的简单解决方案是

.profilePosts div {

background: url("xyz");
background-size: contain;
background-repeat: no-repeat;
width: x;
height: y;

}

我觉得现在回答这个问题有点晚了。无论如何,希望这对将来的人们有所帮助。 我面临的问题,定位卡片的角度。有针对事件数组显示的卡片。如果事件的图像宽度对于卡片来说比较大,图像应该从两边裁剪,高度为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;
}
<div class="container">
     <img src="http://i.stack.imgur.com/2OrtT.jpg"/>
</div>

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

你可以使用css属性object-fit。(“设置替换元素的内容,如<img>或<video>,应该如何调整大小以适应其容器。”)

.cover { object-fit:封面; 宽度:50 px; 身高:100 px; } <img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />

参见这里的例子

IE有一个polyfill: https://github.com/anselmh/object-fit

相关:object-position(指定元素内容在其框内的对齐方式)。