![](/img/trans.png)
[英]How can I resize and crop/letterbox image to completely fill div with image whatever resize
[英]How can i get my image to to completely fill my div?
我正在嘗試創建一個英雄圖像,它將填充 div 到我的網頁。 我試過將寬度和高度設置為 100%,但由於某種原因,圖像只會將 div 填充到大約一半。
這是 CSS 和 HTML我試圖讓圖像填滿整個屏幕,但它對我不起作用
div.hero{ width: 100%; height: 100%; margin:0 auto; } #imghero { max-width: 100%; max-height: 100%; }
<main> <div class="hero"> <img src="https://i.stack.imgur.com/4Xg4w.jpg" alt="laptop" class="imghero"> <h1>Welcome</h1> </div> </main>
您還必須為圖像設置寬度和高度,而不僅僅是最大寬度和最大高度
div.hero{width : 100%; height: 100%;margin:0 auto; } .imghero{max-width: 100%; max-height: 100%; height: 300px; width: 100% !important; }
<main> <div class="hero"> <img src="https://i.stack.imgur.com/4Xg4w.jpg" alt="laptop" class="imghero"> <h1>Welcome</h1> </div> </main>
使用.imghero
而不是#imghero
,您將 imghero 聲明為類
您可以嘗試將背景圖像設置為 div
.hero{ background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQc-z-m2WiHy9yx9AfLg_YEi6mzltIlkaY_JGrIhP8d8mh_wMpB"); background-size: cover; background-repeat: no-repeat; /*this is optional*/ min-height: 500px; }
<main> <div class="hero"> <h1>Welcome</h1> </div> </main>
我不會將圖像直接放在 div 中,而是添加為背景圖像。
<main>
<div class="hero">
</div>
</main>
和 CSS
.hero {
background-image:url(image address here.);
padding-top:300px;
padding-bottom:300px;
}
CSS 中的 padding 為 div 添加了高度,如果你想在那里添加文本,這很方便。
或者你可以用height: auto
替換 padding 來填充整個瀏覽器的高度。
我看到這里的其他人建議使用背景圖像,但我建議使用實際的圖像元素,並使用object-fit: cover
縮放。 這有兩個原因。
這是你如何做到的:
<div class="container">
<img
src="imageurl.jpg"
srcset="*optional*"
sizes="*optional*"
alt="My image"
/>
</div>
.container {
position: relative;
width: 80vw; /* Or whatever size you want */
height: 50vh; /* Or whatever size you want */
}
.container img {
position: absolute;
top: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
如果容器上沒有固定的高度/高度,則可以使用縱橫比,如下所示:
.container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%; /* 16:9 aspect ratio */
}
由於您使用的是img
標簽,因此您無法操縱圖像的寬度和高度,它的 max-width 和 max-height 將是圖像的寬度和高度。
為了讓它跨越整個寬度/高度,您需要將其添加為 background-image 屬性。 然后您可以在div
上設置寬度和高度。
HTML
(注意,這里我們不包括圖像,我們在 CSS 中這樣做):
<main>
<div class="hero imghero">
<h1>Welcome</h1>
</div>
</main>
CSS
:
.hero {
width: 100%;
height: 100%;
margin: 0;
}
.imhero {
width: 100%;
height: 100%;
background-image: url("https://i.stack.imgur.com/4Xg4w.jpg") no-repeat;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.