【问题标题】:100% window height | 100% parent div width100% 窗口高度 | 100% 父 div 宽度
【发布时间】:2013-01-02 13:15:34
【问题描述】:

我想创建一个 HTML 页面:

  • 水平居中显示
  • 整个窗口的高度都是白色背景
  • 包含固定的标题和可滚动的内容

我有两个与 {width: 100%} 和 {height: 100%} 有关的问题。

我的页眉是页面宽度的 100%,而我希望它是其父宽度的 100%。 背景出现在窗口高度的 100% 处,但随后会随着内容向上滚动。

如果能帮助我理解 CSS 在这两种情况下如何处理 100% 值,我将不胜感激。我不是在寻求解决方法:我已经有了。我要求深入了解 CSS 的思维方式。

非常感谢,

詹姆斯

Here's a demo of the issue

这是基本的 HTML:

<!DOCTYPE html>
<head>
<title>Width & Height 100%</title>

<style>
html {
    height:100%;
}

body {
    background: #666;
    height: 100%;
    margin: 0;
}

#container {
    position: relative;
    height:100%;
    background: white;
    width: 400px;
    margin: 0 auto;
    padding: 0 0;
}

#header {
    position:fixed;
    z-index:100;
    background:#ffe;
    /* width:760px; */
    width:100%;
    height:64px;
}

#content {
    position: absolute;
    left:20px;
    width:360px;
    height:360px;
    margin:64px 0 0 0;
    background:#efe;
}
</style>
</head>

<body>
<div id="container">
    <div id="header">
        Fixed header
    </div>

    <div id="content">
        Scrollable content
    </div>
</div>
</body>
</html>

【问题讨论】:

  • 你的情况不是对width和height属性的理解有问题,你的问题是元素的定位问题

标签: css scroll height width


【解决方案1】:

修复标题
将标题位置fixed更改为位置absolute

修复内容高度

* {
    margin: 0;
}
html, body {
    height: 100%;
}
#container{
    min-height: 100%;
    height: auto !important;
    height: 100%;
    background:#efe;
}
#content {
    padding: 64px 20px 0;
}

固定位置的实时示例
http://jsfiddle.net/qB4sD/1/

【讨论】:

  • 我认为你保持不变,如果那是你所追求的。关键在于将高度设置为自动,将最小高度设置为 100%。您还应该对正文和 html 执行此操作。像这样:jsfiddle.net/SQRuB
  • 嗨尼尔斯!非常感谢您的意见。我已经尝试将您的 CSS 更改合并到我的项目中,但我不确定它们是添加还是替换。无论哪种情况,我都没有得到我想要的效果。将标题位置设置为绝对使其随页面滚动,这不是我想要的。
【解决方案2】:

所有这些固定位置都会让你头疼。

关于宽度:盒子模型通常是问题所在。我开始每个 CSS 时将 body 高度和宽度设置为 100%,然后重置我的盒子模型,使其在浏览器中匹配,并将我的所有填充应用到盒子的内部而不是外部:

/* Set box models to match across browsers. */
* {
 box-sizing:border-box;
 -moz-box-sizing:border-box;
 webkit-box-sizing:border-box;
 max-width:100%;
}

然后使用填充在容器上设置宽度,首先是移动宽度,然后是要覆盖的屏幕宽度:

#container {
    padding: 0px 10px;
}
        @media only screen
        and (min-width : 700px) {

            #container {
            padding: 0% 30%;
            }

        }

如需完整版面,您可以访问我的网站: http://instancia.net/fluid-sticky-footer-layout/

我可能应该将移动位添加到该页面。 :)

【讨论】:

  • 你不是把事情复杂化了吗?那么不支持边框框或媒体查询的旧版浏览器呢?
猜你喜欢
  • 2014-11-30
  • 1970-01-01
  • 2016-08-09
  • 2015-02-04
  • 1970-01-01
  • 2013-08-04
  • 2013-04-04
  • 1970-01-01
  • 2012-11-16
相关资源
最近更新 更多