【发布时间】:2015-10-31 19:39:51
【问题描述】:
我一直在 Internet 上查找 min-height 和 height 属性如何作用于 body 和 html 元素。我在很多地方都看到过下面的代码
html {
height: 100%;
}
body {
min-height: 100%;
}
以上可以与其他一些 div 结合使用以获得粘性页脚。另一种说法是要在 body 上设置百分比高度,我们还需要设置 html 的显式高度。
好吧,但是html标签的高度相对于百分比是多少?一些答案说,如果视口的高度为 100%,则它是相对于视口的。现在这个 100% 的视口高度是什么?
这里的帖子说html元素的高度由视口HTML vsBody控制,但我看到的不是这个
HTML 元素的高度可以增加
但是为什么当内容增加时 html 元素的高度也会增加,这可以在 Chrome 开发者工具上看到
代码:
html {
}
.wrapper {
padding-bottom: 3000px;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
}
<html>
<head>
<title>Height</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="header">
Header
</div>
<div class="content">
Content
</div>
<div class="footer">
Footer
</div>
</div>
</body>
</html>
固定的 HTML 元素高度
只有当我明确地将 html 元素的高度设置为 100% 时,它才会得到一个固定的高度:
html {
height: 100%;
}
.wrapper {
padding-bottom: 3000px;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
}
<html>
<head>
<title>Height</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="header">
Header
</div>
<div class="content">
Content
</div>
<div class="footer">
Footer
</div>
</div>
</body>
</html>
这是固定高度:
粘滞页脚
既然 HTML 元素的高度占据了整个内容,为什么我不能通过不在 html 上设置高度或设置最小高度来实现粘性页脚?由于 body 是默认的position: static,如果我定位任何东西,它应该定位在 html 元素上对吗?
但以下都不起作用:/
html {
min-height: 100%;
}
.wrapper {
padding-bottom: 1000px;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
}
<html>
<head>
<title>Height</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="header">
Header
</div>
<div class="content">
Content
</div>
<div class="footer">
Footer
</div>
</div>
</body>
</html>
html {
}
.wrapper {
padding-bottom: 3000px;
}
.footer {
position: absolute;
bottom: 0;
left: 0;
}
<html>
<head>
<title>Height</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="wrapper">
<div class="header">
Header
</div>
<div class="content">
Content
</div>
<div class="footer">
Footer
</div>
</div>
</body>
</html>
- 总之谁能告诉我html的高度和 计算身体元素?
- 为什么上面的粘性页脚不起作用?
参考资料:
【问题讨论】:
-
如果您有单独的问题,请单独发布!!!
-
它们并不完全分开。我猜两者都有相同的答案,因为粘性页脚技巧取决于 body 和 html 元素的高度。
-
在您的第二个代码 sn-p 中,页脚不起作用,因为您需要设置此 css .wrapper{position:relative;} 这将确保页脚正确显示
-
但是我希望它相对于 html 元素,如果我没有将其下的任何元素设置为相对定位,那么 html 元素是否应该相对定位?
-
因为你的父元素,即包装器未设置为 position:relative ,任何 div 的默认设置都是静态的,所以你的父元素,即包装器具有 css position:static 所以当你试图定位你的页脚绝对它无法找到可以用作相对位置的父级