html – CSS高度100%使元素高度超过100%

参见英文答案 > Why does my div height 100% work only when DOCTYPE is removed?                                    5个
以下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>

enter image description here

解决方法

你得到垂直滚动条的原因是因为你告诉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>

除了这个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>

原始代码有两个调整.

>添加显示:flex
>移除高度:100%

Fiddle Demo

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些