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

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

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

填充和拉伸图像示例:

原始图像:

拉伸图片:

填充图片:

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


当前回答

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

.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>

其他回答

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

据我所知,有一个插件可以让这变得简单。

jQuery插件:自动转换<img>为背景样式

<img class="fill" src="image.jpg" alt="Fill Image"></img>

<script>
    $("img.fill").img2bg();
</script>

此外,这种方式也满足了可达性需求。因为这个插件不会从你的代码中删除你的<img>标签,屏幕阅读器仍然会告诉你ALT文本,而不是跳过它。

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

.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>

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

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