【问题标题】:Position sticky always on bottom of viewport [duplicate]始终将粘性定位在视口底部[重复]
【发布时间】:2021-04-25 00:15:44
【问题描述】:

我正在寻找最简单的解决方案,让 div 保持粘性并始终呈现在视口底部。我不想使用 position: fixed 因为该元素将不在文档流中,当我在页面上有更多内容时,它会隐藏其中的一部分而不会触发溢出。

另一方面,当页面上的内容太少时,粘性会出现问题,然后它会立即呈现在该内容之后,而不是一直呈现在视口底部。

是否有一种简单的方法可以仅使用 HTML/CSS 使粘性始终位于视口底部?

【问题讨论】:

标签: html css


【解决方案1】:

使用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>

【讨论】:

  • 当我将 html 和 body 的高度设置为 100% 时,无论我的内容有多短,我都会得到一个滚动条。这是我喜欢的一种方法,但在这种情况下我需要以某种方式移除滚动条。
【解决方案2】:

我在这里看到了两种解决方案。

使用display: flex;

您可以制作由两个容器组成的覆盖整个屏幕 (100vh) 的列布局。

  • 顶级容器将管理页面内容
  • 底部容器将是始终“粘性”的页脚,尽管并非字面上的 CSS 粘性。

例子:

.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;

给定两个容器(mainfooter),您需要在主容器上应用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>

【讨论】:

    【解决方案3】:

    我不确定您的 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2018-06-21
      • 2020-11-30
      • 2011-03-01
      相关资源
      最近更新 更多