参见英文答案 >
Why does my div height 100% work only when DOCTYPE is removed? 5个
以下HTML很简单,可以满足我的需求.绿色的身体向下伸展以填满窗户.
以下HTML很简单,可以满足我的需求.绿色的身体向下伸展以填满窗户.
<body style="margin:0"> <div style="height:100%;display:flex;flex-direction:column"> <div style="background:#d0d0ff"> This is a header </div> <div style="background:#d0ffd0;flex-grow:1"> This is the body. </div> </div> </body>
但是,如果我用一些弹性列替换该正文文本,并且我给它们高度:100%因为我希望它们伸展到底部,newdiv实际上得到的高度大于它的容器的100%并导致所有内容滚动.为什么100%不是100%在这里?
<body style="margin:0"> <div style="height:100%;display:flex;flex-direction:column"> <div style="background:#d0d0ff"> This is a header </div> <div style="background:#d0ffd0;flex-grow:1"> <!-- The new part --> <div id='newdiv' style="display:flex;flex-direction:row; height:100%"> <div style="background:#ffd0d0"> Col 1 </div> <div> Col 2 </div> </div> </div> </div> </body>
解决方法
你得到垂直滚动条的原因是因为你告诉col1和col2的div父级是高度:100%.这本身就为视口提供了全高度.
从您的代码:
<div id='newdiv' style="display:flex; flex-direction:row; height:100%"> <div style="background:#ffd0d0"> Col 1 </div> <div> Col 2 </div> </div>
所以当浏览器进行高度计算时,结果如下:
100% + (computed height of header div) > viewport height = vertical scrollbar
不要使用定义的高度,而是考虑让flexBox完成工作.默认情况下,弹性项目沿着横轴展开容器的整个长度.
因此,通过简单地声明display:flex,子元素将展开以填充所有可用空间(没有垂直滚动).但由于高度规则将覆盖此弹性设置,因此我们需要从任何弹性项目中移除高度:100%.
html,body { height: 100%; }
<body style="margin:0"> <div style="height:100%;display:flex;flex-direction:column"> <div style="background:#d0d0ff"> This is a header </div> <div style="background:#d0ffd0;flex-grow:1; display: flex;"><!--adjustment here--> <div id='newdiv' style="display:flex;"><!--adjustment here--> <div style="background:#ffd0d0; display: flex;"> Col 1 </div> <div> Col 2 </div> </div> </div> </div> </body>
原始代码有两个调整.