保持寬高比顯示全景橫幅圖片,避免裁剪或留白,是網頁設計中常見的挑戰。本文將介紹兩種方法,確保16:3比例的橫幅圖片完整顯示,且不失真。
使用Object-fit: contain;會造成兩側留白,而object-fit: cover;則會裁剪圖片,如下圖所示:
原始圖片:
以下提供兩種解決方案:
方法一:利用img標簽和css
此方法通過設置容器的寬高比,并使用object-fit: cover;來確保圖片填充容器,但不會被裁剪。
html代碼:
<div class="image-container"> @@##@@ </div>
CSS代碼:
.image-container { width: 100%; padding-top: calc(100% / (16 / 3)); /* 16:3比例 */ position: relative; overflow: hidden; } .image-container img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; }
方法二:使用背景圖片
此方法將圖片設置為容器的背景,利用background-size: cover;實現填充,并用background-position: center;和background-repeat: no-repeat;確保圖片居中且不重復。
HTML代碼:
<div class="image-container"></div>
CSS代碼:
.image-container { width: 100%; padding-top: calc(100% / (16 / 3)); /* 16:3比例 */ background-image: url('your-image.jpg'); background-size: cover; background-position: center; background-repeat: no-repeat; }
兩種方法都能有效解決問題,選擇哪種方法取決于你的項目需求和偏好。 記住替換your-image.jpg為你的圖片路徑。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END