[英]Div with background-image and height auto
我試圖在background-image
顯示div
。 我嘗試以與使用img
相同的方式執行此操作,但它不起作用:
在IMG內
HTML
<img class="scale" src="../../../assets/images/van-landing-2.JPG">
CSS
.scale {
max-width: 100%;
height: auto;
width: auto\9;
/* ie8 */
}
這非常有效。 它顯示的圖像占據了我的屏幕的100%,高度應該是成比例的。
照片
然而,當我嘗試使用div時,它不起作用。 它沒有顯示任何導致它沒有設置特定高度,因此它什么也沒顯示。
在DIV之內
HTML
<div class="i-van"></div>
CSS
.i-van {
background-image: url("../../../assets/images/van-landing.JPG");
max-width: 100%;
height: auto;
width: auto\9;
/* ie8 */
}
照片
我怎么能這樣做? 我嘗試過使用min-height
並顯示它但只是最小高度。 我想展示一切。
background-image
屬性用於向元素添加背景。 這意味着該元素中的內容決定了它的大小。 另外, height:auto
由元素內容解釋。
您可以嘗試使用height:100%
前提是父元素也有定義的高度值。 這會將元素拉伸到最高的高度並相應地縮放背景圖像。
如果您希望以圖像本身的精確尺寸或縱橫比顯示圖像,則需要使用圖像的精確width
和height
來定義元素。
但是,從語義角度來看,您應該確定您顯示的圖像是頁面內容的一部分還是設計的裝飾部分。 通常,對於不是background-image
內容和background-image
圖像,應使用<img />
標記。
您必須聲明背景div的有效高度。 正如Maneesh所說的height:auto
取元素內容的高度。
檢查片段! :)
使用FLEXBOX的代碼
body { margin: 0; } .i-van { display: flex; align-items: center; justify-content: center; background-image: url(https://www.planwallpaper.com/static/images/3865967-wallpaper-full-hd_XNgM7er.jpg); background-size: cover; background-position: center; max-width: 100%; height: 100vh; } #div-inside { font-size: 100px; color: white; }
<div class="i-van"> <div id="div-inside"> HELLO </div> </div>
具有位置絕對的代碼
body { margin: 0; } .i-van { position: relative; background-image: url(https://www.planwallpaper.com/static/images/3865967-wallpaper-full-hd_XNgM7er.jpg); background-size: cover; background-position: center; max-width: 100%; height: 100vh; } #div-inside { position: absolute; top: 50%; /* position the top edge of the element at the middle of the parent */ left: 50%; /* position the left edge of the element at the middle of the parent */ transform: translate(-50%, -50%); /* This is a shorthand of translateX(-50%) and translateY(-50%) */ font-size: 100px; color: white; }
<div class="i-van"> <div id="div-inside"> HELLO </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.