![](/img/trans.png)
[英]How can I make a div 100% of the browser window height, but with a top and bottom margin?
[英]How can I make a div 100% of window height?
我只想要一個側邊欄,它將是窗口高度的100%,但除此之外沒有任何作用:
#sidebarBack {
background: rgba(20, 20, 20, .3);
position: fixed;
width: 250px;
height: 100%;
left: 0;
}
我不希望有position: fixed
,因為我有可水平滾動的內容,所以固定的部分將保留,好,固定。
有沒有辦法做這樣的事情,也許有relative
或absolute
位置?
這是一個快速的小提琴,只是為了測試和解釋: JSFiddle
你可以使用新的,非常有用的 - 我無法想象的W3C-so-long vh
CSS單元:
height:100vh;
tl; dr - 在你的CSS中添加html, body {height:100%;}
。
CSS中的百分比值是從已聲明高度的某個祖先繼承的。 在您的情況下,您需要告訴您的側邊欄的所有父母是100%身高。 我假設#sidebarBack
是body
的直接孩子。
基本上,上面的代碼告訴#sidebarBack
是其父級的100%高度。 它的父母(我們假設)是body
,所以你需要設置height: 100%;
在body
上也是如此。 但是,我們不能止步於此; body
從html
繼承高度,所以我們還需要設置height: 100%;
在html
。 我們可以在這里停止,因為html
從viewport
繼承了它的屬性,它已經聲明了100%
高度。
這也意味着如果您最終將#sidebar
放在另一個div
,那么該div
也需要height:100%;
。
這是一個更新的JSFiddle 。
將您的CSS更改為:
html, body {
height:100%;
}
#sidebar {
background: rgba(20, 20, 20, .3);
width: 100px;
height: 100%;
left: 0;
float:left;
}
section#settings {
width:80%;
float:left;
margin-left:100px;
position:fixed;
}
首先,告訴body元素填充窗口,而不是縮小到內容的大小:
body { position: absolute; min-height: 100%; }
通過使用min-height
而不是height
,當內容長於窗口時,將允許主體擴展超出窗口的高度(即,這允許在需要時進行垂直滾動)。
現在,將“#sidebar”設置為position:absolute
,並使用top:0; bottom:0;
top:0; bottom:0;
強制它填充父元素的垂直空間:
#sidebar {
position: absolute;
top:0; bottom:0;
left: 0;
width: 100px;
background: rgba(20, 20, 20, .3);
}
這里有幾個jsFiddles:
正如您將看到的,在兩個示例中,我都在“#settings”部分保留了寬度設置,從而顯示水平滾動按您的要求工作。
請嘗試以下方法
#sidebarBack {
background: rgba(20, 20, 20, .3);
position: fixed;
width: 250px;
top:0;
bottom:0;
left: 0;
}
嘗試這個 -
html,body{height:100%;}
#sidebar {
background: rgba(20, 20, 20, .3);
/*position: fixed;*/
width: 100px;
height: 100%;
left: 0;
float:left;
}
section#settings {
width: 62%;
height: auto;
display: inline-block;
position: relative;
margin-left: 100px;
float:left;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.