为div元素拟合不同大小的图像



我们正在生成圆圈内的球员图像,如下所示:

div.intable-player-image {
border: 1px solid #666;
border-radius: 50%;
margin: 1px auto;
max-height: 25px;
overflow: hidden;
width: 25px;
}
<div style="display: flex; width: 150px; ">
<div class="intable-player-image" style="pointer-events: auto;">
<a class="logo" href="/">
<img src="https://storage.googleapis.com/cbb-image-files/PlayerHeadshots/105304-965025.png" alt="player-face" style="width: 100%;/* height: 100%; */">
</a>
</div>
<div class="intable-player-image" style="pointer-events: auto;">
<a class="logo" href="/">
<img src="https://storage.googleapis.com/cbb-image-files/PlayerHeadshots/105676-963793.png" alt="player-face" style="width: 100%;">
</a>
</div>
<div class="intable-player-image" style="pointer-events: auto;">
<a class="logo" href="/">
<img src="https://storage.googleapis.com/cbb-image-files/PlayerHeadshots/104923-1321451.png" alt="player-face" style="width: 100%;">
</a>
</div>
</div>

玩家图像是各种形状和大小的。有些图像的宽度大于高度(第一张图像),有些图像的高度大于宽度(第二、第三张图像)。我们的目标是用一种"一刀切"的方法来显示尽可能合适的大小。

在上面的例子中,由于空白显示,第一张图像是主要问题。关于我们如何调整样式来改善第一张图片的贴合度,而不会弄乱第二张和第三张图片,有什么建议吗?作为奖励,在第二张图像中让玩家的脸看起来稍微大一点也是对当前解决方案的改进。

object-fitobject-position用于控制其容器内元素的定位和缩放。

object-fit属性指定图像应该如何调整大小以适合其容器,同时保留其长宽比。

object-position属性定义了图像在其容器中的位置。

div.intable-player-image {
border: 1px solid #666;
border-radius: 50%;
margin: 1px auto;
max-height: 150px;
overflow: hidden;
width: 150px;
display: block;
}
div.intable-player-image img {
object-fit: cover;
object-position: center 10%;
width: 100%;
height: 100%;
}
<div style="display: flex; width: 500px; ">
<div class="intable-player-image" style="pointer-events: auto;">
<img src="https://storage.googleapis.com/cbb-image-files/PlayerHeadshots/105304-965025.png" alt="player-face" style="width: 100%;/* height: 100%; */">
</div>
<div class="intable-player-image" style="pointer-events: auto;">
<a class="logo" href="/">
<img src="https://storage.googleapis.com/cbb-image-files/PlayerHeadshots/105676-963793.png" alt="player-face" style="width: 100%;">
</a>
</div>
<div class="intable-player-image" style="pointer-events: auto;">
<a class="logo" href="/">
<img src="https://storage.googleapis.com/cbb-image-files/PlayerHeadshots/104923-1321451.png" alt="player-face" style="width: 100%;">
</a>
</div>
</div>

在示例中,object-fit: cover;用于设置图像覆盖整个容器,同时保持其长宽比。这意味着图像将被缩放以填充容器,同时从宽度或高度裁剪任何多余的部分,以完全适合容器div。

object-position: center 10%;用于设置图像水平居中,距离容器顶部10%。这意味着图像将水平居中,并且图像的前10%将被裁剪。

这些属性一起确保图像被缩放以适合其容器div,同时保持其长宽比并保持所需的位置。

如果你有一个嵌套在div元素中的图像,你所需要做的就是将图像的max-width设置为100%,它将被限制在div的大小。

<div>
<img src="your-source" alt="dont-forget-good-alternative-text">
</div>
div {
width: 100px;
}
img {
max-width: 100%;
}

在上面的例子中,图像的最大宽度将由父div决定,并且不会超过100px。

最新更新