【发布时间】:2021-04-25 00:15:44
【问题描述】:
我正在寻找最简单的解决方案,让 div 保持粘性并始终呈现在视口底部。我不想使用 position: fixed 因为该元素将不在文档流中,当我在页面上有更多内容时,它会隐藏其中的一部分而不会触发溢出。
另一方面,当页面上的内容太少时,粘性会出现问题,然后它会立即呈现在该内容之后,而不是一直呈现在视口底部。
是否有一种简单的方法可以仅使用 HTML/CSS 使粘性始终位于视口底部?
【问题讨论】:
我正在寻找最简单的解决方案,让 div 保持粘性并始终呈现在视口底部。我不想使用 position: fixed 因为该元素将不在文档流中,当我在页面上有更多内容时,它会隐藏其中的一部分而不会触发溢出。
另一方面,当页面上的内容太少时,粘性会出现问题,然后它会立即呈现在该内容之后,而不是一直呈现在视口底部。
是否有一种简单的方法可以仅使用 HTML/CSS 使粘性始终位于视口底部?
【问题讨论】:
使用bottom: 0,例如:
html, body {
height: 100%;
}
/* need something scrollable: */
.dummy {
background: #eee;
height: 200%;
border: #f00 1px solid;
}
.stick-bottom {
position: sticky;
bottom: 0;
}
...
<div class="dummy">Lorem ipsum</div>
<div class="stick-bottom">bottom</div>
【讨论】:
我在这里看到了两种解决方案。
display: flex;
您可以制作由两个容器组成的覆盖整个屏幕 (100vh) 的列布局。
例子:
.container {
height: 100vh;
background: blue;
display: flex;
flex-direction: column;
}
.content {
height: 100%;
overflow: auto;
}
footer {
height: 60px;
background: red;
}
body {
margin: 0;
padding: 0;
}
<div class="container">
<div class="content">
<div>Ping</div>
<div>Ping</div>
<div>Ping</div>
<div>Ping</div>
<div>Ping</div>
<div>Ping</div>
<div>Ping</div>
<div>Ping</div>
</div>
<footer>This is the footer</footer>
</div>
position: sticky;
给定两个容器(main 和footer),您需要在主容器上应用min-width: calc(100vh - footerHeight),同时将页脚贴在容器底部。
这意味着main 容器将始终至少覆盖100vh - footerHeight。
例子:
body {
padding: 0;
margin: 0;
}
footer {
background: red;
position: sticky;
bottom: 0;
height: 60px;
}
.content {
min-height: calc(100vh - 60px);
display: flex;
flex-direction: column;
position: relative;
}
<div class="content">
<p>Ping</p>
<p>Ping</p>
<p>Ping</p>
<p>Ping</p>
<p>Ping</p>
</div>
<footer>This is the footer</footer>
【讨论】:
我不确定您的 UI 有多复杂,但对于不使用 CSS 位置的简单布局,您可以使用元素高度来使 div 保持粘性并始终呈现在视口底部:
HTML
<div class="full">
<h2>body</h2>
</div>
<div class="sticky">
<h4>Sticky</h4>
</div>
CSS
html, body {
height: 100%;
}
.full {
min-height:calc(100% - 70px);
background:#ccc;
}
.sticky {
height:70px;
text-align: center;
background:#000;
color:#fff;
}
【讨论】: