![](/img/trans.png)
[英]Trouble making a div with a background-image with fixed height and width responsive
[英]How to get height of responsive div's background-image
我有一個帶背景圖像的div。 該div里面還有其他內容,例如我的導航。
我希望這個div具有與背景圖片相同的高度。
我的嘗試是:
.bg { width: 100 %; display: inline - block; } .bg::after { background: url('/images/desktop2.png') no - repeat center top; background - size: 100 % auto; content: ""; opacity: 0.8; top: 0; left: 0; bottom: 0; right: 0; position: absolute; z - index: -1; }
<div class="bg"> <div class="navigation"></div> <div>Other contents</div> </div> <div class="container"> <div>First content</div> <div> <Second content</div> ... </div>
這樣,我使bg div具有圖像高度,但是container
div到達div背景圖像內部。
我需要bg div僅具有導航和其他內容。
在這個div之后,我需要帶有其內容的容器
您可以使用偽和填充來擴展容器的高度,以適合背景圖像的已知比例:
例
.bg-ratio { background: url(https://baconmockup.com/1024/576) no-repeat red/* only to check ratio height */ ; background-size: 100% auto; overflow: hidden; /* to see the floatting pseudo */ font-size: 5vmax; color: white; text-shadow:0 0 1px black; } .bg-ratio:before { content: ''; float: left; padding-top: 56.25%; /* (576px / 1024px) x 100 */ } body { width: 80%; margin: auto; }
<div class="bg-ratio"> <header>content in here</header> <main> <p>play full page and resize window's width</p> </main> </div>
如何增加元素的高度以匹配比例?
垂直邊距或填充百分比值將根據父級的寬度進行計算。 padding-top : 100%
等於父級的width
。 如果將其設置為偽,則空框將擴展為正方形(比率1:1) 。
資料來源: https : //www.w3.org/TR/CSS2/box.html#padding-properties
<length>
指定固定寬度。
<percentage>
即使是對於“ padding-top”和“ padding-bottom”,百分比也是相對於所生成的盒子的包含塊的寬度來計算的。 如果包含塊的寬度取決於此元素,則結果布局在CSS 2.1中未定義。
與邊距屬性不同,填充值的值不能為負。 與邊距屬性類似 , 填充屬性的百分比值是指所生成框的包含塊的寬度 。
如果容器跨越整個屏幕,則可以通過height
或min-height
使用vw
單位,並放置偽指令。
.bg-ratio { background: url( https://baconmockup.com/1200/100) no-repeat red /* only to check ratio height */; background-size:100% auto; height:8.33vw;/* (100px / 1200px) x 100 */ } body { margin:auto; }
<header class="bg-ratio"> <div>content in here</div> </header> <main>play full page and resize window's width</main>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.