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

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

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

填充和拉伸图像示例:

原始图像:

拉伸图片:

填充图片:

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


当前回答

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

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

其他回答

增强了@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 ..." />

试试这个:http://jsfiddle.net/D7E3E/4/

使用溢出容器:隐藏

编辑:@多米尼克·格林打败了我。

为了适应图像在全屏试试这个:

平铺方式:圆形;

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

你可以通过“伸缩”显示来实现。对我来说!:

.avatar-img { display: flex; justify-content: center; align-items: stretch; border-radius: 50%; border: 1px solid #dee2e6; height: 5.5rem; width: 5.5rem; overflow: hidden; } .avatar-img > img { flex-grow: 1; object-fit: cover; } <div> <div class="avatar-img"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqczw3Fb_TYsj0hbPEy0u7Ay2bVq1KurD6hw&amp;usqp=CAU" alt="Test!'s profile photo"> </div> <div class="avatar-img"> <img src="https://i.pinimg.com/236x/a1/37/09/a137098873af3bf6180dd24cbe388ae9--flower-iphone-wallpaper-wallpapers-flowers.jpg" alt="Test!'s profile photo"> </div> </div>