背景: 圖片展示不僅僅可以設置寬高, 還有對應的css屬性
object-fit 屬性
指定元素的內容應該如何去適應指定容器的高度與寬度。
object-fit 一般用於 img 和 video 標簽,一般可以對這些元素進行保留原始比例的剪切、縮放或者直接進行拉伸等。
html代碼:
<div style='height:300px;width:300px; background-color: pink; display: block;'>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="border: 1px solid red;">
</div>
<p>原圖片標簽</p>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="">
<p>object-fit: fill; 拉伸/縮小填充</p>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: fill;">
<p>object-fit: contain; 保持寬高縮放填充</p>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: contain;">
<p>object-fit: cover; 保持寬高比填充,超出部分裁剪</p>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: cover;">
<p>object-fit: none; 保持寬高比填充,超出部分裁剪</p>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: none;">
<p>object-fit: scale-down; 內容的尺寸與 none 或 contain 中的一個相同,取決於它們兩個之間誰得到的對象尺寸會更小一些</p>
<img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: scale-down;">
css代碼:
div {
margin: 10px;
display: inline-block;
}
img {
height: 300px;
width: 300px;
border: 1px solid red;
}