[英]CSS crop image to fit screen width while keeping the original height of the image
我正在嘗試在main-content
如背景圖像)的末尾顯示圖像(6000 像素寬度,300 像素高度)。 圖像應該適合屏幕的寬度,但保持原高度。
換句話說,總是在中心裁剪圖像,而 x-crop 的寬度是屏幕寬度大小,高度裁剪是圖像的原始高度。
我制作了寬度為 6000 像素的圖像,以便適合所有屏幕。
下面的代碼並不像預期的那樣工作,它很明顯,它只是顯示原始 img,同時縮放高度以保持相對於屏幕寬度的縱橫比。
newnewwaves.svg : http://svgshare.com/i/3DT.svg
我想如何顯示: https : //ibb.co/e80Ddw
HTML:
<div class="main-content">
...content
<div id="header-waves">
<img src="/assets/images/newnewwaves.svg" alt="">
</div>
</div>
CSS:
.main-content {
position: relative;
}
#header-waves {
position: absolute;
left: 0;
bottom: 0;
}
#header-waves img {
width: 100%;
height: auto;
display: block;
}
您可以將圖像放在width: 100%
的容器中,並將溢出屬性設置為隱藏。
使用flexbox
將圖像在此容器中居中。
請注意,如果您將其設為全屏並調整瀏覽器大小,則此代碼段更容易測試...
#header-waves { width: 100%; overflow: hidden; display: flex; justify-content: center; }
<div class="main-content"> <div id="header-waves"> <img src="https://placehold.it/6000x300" alt=""> </div> </div>
試試這個:
.img-class {
width: 100%;
overflow: hidden;
display: flex;
justify-content: center;
object-fit: cover;
}
這將有助於通過限制寬度和裁剪圖像使其居中來保持縱橫比。
如果這不起作用,請嘗試以下操作:
.img-class {
width: 100%;
height: 400px; /* Set your fixed Limit */
background-size: cover;
}
您可以使用 background: url(...) 來做到這一點,就像示例一樣..
.main-content { background: url('http://via.placeholder.com/6000x300'); background-size: auto 100%; width:100%; height:300px; }
<div class="main-content"> ...content </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.