[英]CSS: dynamically div-height
我有一個帶有頁眉,頁腳和中心內容部分的CSS端。
我想使用瀏覽器窗口的全部高度。
例如
header - height: 20vh
content - height: 60vh
footer - height: 20vh
那是100vh,整個窗口。
是否有可能通過CSS動態地實現這種分手, 而無需使用與應用程序狀態有關的javascript手動操縱樣式(頁腳處於打開還是關閉狀態)?
可以說,如果禁用頁腳,則內容應具有80vh,如果打開則應具有60vh。
為什么不為此使用flexbox或grid?
設置頁眉和頁腳的最小高度(以vh為單位),然后為內容添加100%的高度。
然后,flexbox將所有可用空間用於內容,但仍呈現其他元素的最小高度。
function changeVisibility() { document.querySelector( 'footer' ).classList.toggle( 'hidden' ); }
*, *::before, *::after { margin: 0; box-sizing: border-box; } .container { width: 100vw; height: 100vh; display: flex; flex-direction: column; } header { /* set default height */ flex-basis: 10vh; background: lightyellow; } .content { /* use all available space */ flex-grow: 1; background: pink; } footer { /* set default height */ flex-basis: 20vh; background: lightblue; } .hidden { display: none; }
<div class="container"> <header>header <button onclick="changeVisibility()">toggle footer</button></header> <div class="content">content</div> <footer>footer</footer> </div>
我認為這段代碼將通過css幫助您動態調整高度
(僅在一個盒子中添加更多內容,然后增加3個盒子的高度)
#main { width: 220px; height:auto; border: 1px solid black; display: -webkit-flex; /* Safari */ display: flex; } #main div { -webkit-flex: 1; /* Safari 6.1+ */ -ms-flex: 1; /* IE 10 */ flex: 1; }
<!DOCTYPE html> <html> <head> </head> <body> <div id="main"> <div style="background-color:coral;">RED</div> <div style="background-color:lightblue;">BLUE</div> <div style="background-color:lightgreen;">Green div with more content. Green div with more content.</div> </div> <p><b>Note:</b> Internet Explorer 9 and earlier versions do not support the flex property.</p> <p><b>Note:</b> Internet Explorer 10 supports an alternative, the -ms-flex property. IE11 and newer versions fully support the flex property (do not need the -ms- prefix).</p> <p><b>Note:</b> Safari 6.1 (and newer) supports an alternative, the -webkit-flex property.</p> </body> </html>
您可以在Flexbox上執行此操作,在其中您可以設置#content
以使用flex: 1
保留剩余的垂直空間:
function display() { document.getElementById('footer').classList.toggle('display'); }
html, body {width:100%;height:100vh;margin:0} body { /* or any other parent element / flex-container */ display: flex; /* displays children inline by default thats why you need to change its direction from row (default) to column */ flex-direction: column; /* stacks children vertically */ } header, footer { height: 20vh; } #content { flex: 1; /* takes the remaining vertical space no matter if the footer is present or not or even if its the only child element inside the flex-container */ background: Aquamarine; } .display {display:none}
<header>HEADER</header> <div id="content">CONTENT <a href="#" onclick="display()">Toggle height</a></div> <footer id="footer">FOOTER</footer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.