我在可變縱橫比的矩形 div 中有一個方形影像。我設定了它的屬性 object-fit: contains; 想法是它會動態調整大小以填充 div 但不超過它。這按預期作業。但是,我有一個影像映射,這就是問題所在:影像的框模型延伸到填充矩形 div,盡管實際影像只占據了它的一部分。有什么辦法可以限制 boxmodel 只占用影像使用的空間,或者以某種方式在 javascript 中獲取有關該空間的資訊?
謝謝!
uj5u.com熱心網友回復:
您可以使用width: 100%、height: 100%和object-fit: cover或 更好的選擇background-image、background-size: cover和background-repeat: no-repeat。
.img-container {
width: 400px;
height: 400px;
background: gray;
}
#img1 {
background-image: url(https://picsum.photos/600/200);
background-size: cover;
background-repeat: no-repeat;
}
#img2 {
width: 100%;
height: 100%;
object-fit: cover;
}
<p>Use background (the better option)</p>
<div class="img-container" id="img1"></div>
<br>
<p>Use full width/height and object-fit</p>
<div class="img-container">
<img src="https://picsum.photos/600/200" id="img2">
</div>
在這里了解這些:
第一個解決方案:
- 背景圖片
- 背景尺寸
- 背景重復
第二種解決方案:
- 寬度和高度(尺寸)
- 物件擬合
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527397.html
