【发布时间】:2021-01-08 02:13:02
【问题描述】:
我的 body 元素有问题。它似乎填充了 100% 的屏幕。但是,如果您将浏览器拖小然后向下滚动 - 主体不会延伸。
请参阅this jsFiddle 作为主要示例。
【问题讨论】:
我的 body 元素有问题。它似乎填充了 100% 的屏幕。但是,如果您将浏览器拖小然后向下滚动 - 主体不会延伸。
请参阅this jsFiddle 作为主要示例。
【问题讨论】:
height: 100%;是网站显示窗口的高度,而不是网站的高度,导致向下滚动时背景变紫。
只需添加这个:
html { background: green; }
并删除
body { background: green; }
让背景始终为绿色。 (JSFiddle)
【讨论】:
我相信THIS FIDDLE 回答了这个问题。我一直在生产中使用它,并且效果很好。
HTML:
<html>
<body>
<div class="main-wrapper contain">
<section class="main-content">
Main Content
</section> <!-- end .main-wrapper -->
<div class="other-thing">
Other thing for example.
</div>
</div> <!-- .main-wrapper -->
</body>
</html>
CSS:
/* hard reset */
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
position: relative;
padding: 0; margin: 0;
}
/* micro clear fix (clears floats) */
.contain:before,
.contain:after {
content: " "; /* 1 */
display: table; /* 2 */
}
.contain:after {
clear: both;
}
.contain {
*zoom: 1;
}
html {
height: 100%; /* 01 */
/* tells html to go ahead and feel free to be 100% height */
}
body {
min-height: 100%; /* 02 */
/* expands to push html to the limit */
}
.main-wrapper {
/* overflow: hidden; */
/* in this case - forces wrapper to contain content (like a clear-fix) */
/* use clear fix instead */
}
/* if you see yellow - we are failing */
.main-content {
width: 100%;
float: left;
}
.other-thing {
width: 100%;
float: left;
}
我已经对此进行了测试 - 假设您保留了所有容器和实际包含的东西,它似乎在所有情况下都有效。这个溢出肯定有缺点:隐藏;否则人们不会使用 clear-fix。所以 - 我很想听到更多的意见。
或者,我认为 html 和 body 可以是 100%,然后 .main-wrapper 可以是 min-height: 100%;这也有效。基本上 - 有些东西需要迫使它的所有容器伸展。为了做到这一点,所有这些容器都必须设置为 100%,以便他们记住他们有这种能力。还是我将 div 拟人化太多了...
2021 年更新:
网络的本质是允许内容定义“形状”或“空间”或任何你想称呼它的东西......所以 - 身体并不真正知道它有多“高”。它知道它是 100% 宽度,因为它是块级元素。所以,除非你告诉 HTML 是 height: 100%,然后是每个孩子……那么他们就不会真正知道“100%”的真正含义。 100% 什么?对于仪表板应用程序和桌面全屏布局,您可能需要设置高度(但在大多数情况下不是) - 现在可以使用 100vh 单位。一般规则:让内容决定它的父元素的大小并与 Web 的性质一起工作。 (忽略上面的所有代码!现在是 2021 年:flex-box + grid!:)
【讨论】:
只需从您的<body> 中删除height: 100%; 并从您的<figure> 中删除height: 300px;,您就可以开始了。
您也可以使用此代码:http://jsfiddle.net/Asustaba/LBu8z/8/
【讨论】:
1) 如果你想让 body 填满整个屏幕,同时解决 2 个问题(由于 body 具有动态内容)
现在您可以为此使用 min-height:100vh,这意味着 100% 的视口高度: http://jsfiddle.net/LBu8z/89/
除 Opera Mini 外,所有浏览器均支持:caniuse.com/#search=vh
2)如果你想要一个固定的背景图片,那么我建议拉伸一个固定位置的body:after
我在生产中需要这个解决方案,因为 background-sizing:cover 在固定的背景下无法正常工作,因此我必须制作 body:after 固定并且背景图像不固定。你可以在这里查看:https://www.doklist.com/
body:after{
content:"";
background:green;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
z-index:-1;
}
3) 如果你只想用 body 来做,那么:用溢出滚动拉伸一个固定的 body。但请注意,它可能会干扰某些元素(例如引导工具提示和弹出框)
body {
background: green;
overflow-y:scroll;
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
}
【讨论】: