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

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

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

填充和拉伸图像示例:

原始图像:

拉伸图片:

填充图片:

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


当前回答

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

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

其他回答

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

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

你可以使用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(指定元素内容在其框内的对齐方式)。

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

.profilePosts div {

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

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

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

你必须在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也不工作