首页 > 解决方案 > 粘在可滚动元素底部的位置

问题描述

我无法让页脚粘在可滚动块元素的底部。它仅在内容(在本例中为表格)大于容器高度时才有效。我如何总是让页脚粘在底部?

我尝试position: absolute改用,但是当用户滚动时它保持不变。

.container {
  position: relative;
  overflow-y: scroll;
  height: 150px;
  display: block;
  border: solid 1px black;
}

.footer {
  position: sticky;
  right: 0;
  bottom: 0;
  float: right;
  background-color: lightblue;
}
<div class="container">
  <table>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
  </table>
  <div class="footer">Footer</div>
</div>
<br/>
<div class="container">
  <table>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
  </table>
  <div class="footer">Footer</div>
</div>

标签: htmlcss

解决方案


您需要将显示更改.container为 flex

display: flex;
flex-direction: column;

并且.footer需要有一个margin-top: auto;

请参阅此处的代码:

.container {
  position: relative;
  overflow-y: scroll;
  height: 150px;
  border: solid 1px black;
  display: flex;
  flex-direction: column;
}

.footer {
  position: sticky;
  right: 0;
  bottom: 0;
  float: right;
  background-color: lightblue;
  margin-top: auto;
}
<div class="container">
  <table>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
  </table>
  <div class="footer">Footer</div>
</div>
<br/>
<div class="container">
  <table>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
  </table>
  <div class="footer">Footer</div>
</div>

在这个例子中,页脚占据了容器的整个宽度,但是如果你需要,这很容易在样式中修复。


推荐阅读