微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐