[英]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.