html - 为什么 DIV 容器只显示像素而不显示百分比

标签 html css

我只是想用 CSS 设计一个简单的聊天用于学习目的,但我不明白,为什么 2 DIV 容器没有像我希望的那样炫耀。

这是我当前的代码:

<!DOCTYPE HTML>
<html>
<head>
    <title>Chat</title>
    <meta charset="UTF-8">

    <style type="text/css">
        * {
            font-size: 36px;
        }

        #messages {
            height: 95%;/* Does not work but for example 500px works */
            width: 80%;
            float: left;
            background: grey;
            overflow: auto;
        }

        #users {
            height: 95%;/* Does not work but for example 500px works */
            width: 20%;
            background: dimgrey;
            overflow: auto;
        }

        input {
            width: 100%;
            height: 5%;
            background: lightgrey;
        }
    </style>

</head>

<body>
    <section>
        <div id="messages"></div>
        <div id="users"></div>
        <input type="text">
    </section>
</body>

那么为什么它对 px 起作用而对 % 不起作用呢?

最佳答案

当使用百分比表示高度时,高度是相对于 parent 而言的,因此您需要建立一个基线。通常这是通过设置 html 和 body 元素的高度来完成的。在您的情况下,您还需要在该部分进行设置:

html, body, section {
    height:100%;
}

jsFiddle example

关于html - 为什么 DIV 容器只显示像素而不显示百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941575/

相关文章:

html - 当我找不到 <img> 标签时,如何从网站获取图片?

html - 更改 HTML <g> 大小

html - 页面不会随 DIV 展开

javascript - 如何访问 JQUERY 中的数组元素?

javascript - 卡在 jQuery 加载方法上

html - Swiper slider SVG 图标有时不显示在 Angular Material svg 图标中

javascript - 如何在 HTML , CSS 中将多个图像卡保持在同一行

javascript - jQuery 同位素/砌体排水沟问题

javascript - 使用 Jcrop 裁剪上传的图像

html - 使用 div 隐藏的折叠输入类型