美文网首页HTML+CSS视觉艺术
5种实现CSS底部固定的方法

5种实现CSS底部固定的方法

作者: Liebling_zn | 来源:发表于2021-05-31 15:51 被阅读0次

我们经常会遇到到需要实现底部固定控件的界面,比如详情页,下面就罗列5个常用的方法

方法1:全局增加一个负值下边距等于底部高度

有一个全局的元素包含除了底部之外的所有内容。它有一个负值下边距等于底部的高度。
html代码:

<body>
  <div class="wrapper">
      content
    <div class="push"></div>
  </div>
  <footer class="footer"></footer>
</body>

CSS代码:

html, body {
  height: 100%;
  margin: 0;
}
.wrapper {
  min-height: 100%;

  /* Equal to height of footer */
  /* But also accounting for potential margin-bottom of last child */
  margin-bottom: -50px;
}
.footer, 
.push {
  height: 50px;
}

这个代码需要一个额外的元素.push等于底部的高度,来防止内容覆盖到底部的元素。这个push元素是智能的,它并没有占用到底部的利用,而是通过全局加了一个负边距来填充。

方法2:底部元素增加负值上边距

虽然这个代码减少了一个.push的元素,但还是需要增加多一层的元素包裹内容,并给他一个内边距使其等于底部的高度,防止内容覆盖到底部的内容。
HTML代码:

<body>
  <div class="content">
    <div class="content-inside">
      content
    </div>
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}

方法3:使用calc()计算内容的高度

HTML

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

.content {
  min-height: calc(100vh - 70px);
}
.footer {
  height: 50px;
}

给70px而不是50px是为了为了跟底部隔开20px,防止紧靠在一起。

方法4:使用flexbox

HTML:

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}

方法5:使用grid布局

HTML:

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}
.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}

相关文章

  • CSS粘住固定底部的5种方法

    CSS粘住固定底部的5种方法

  • CSS固定底部的方法

    1. 使用flexbox布局实现 HTML: CSS: 全局增加一个负值下边距等于底部高度 html: CSS:

  • 5种实现CSS底部固定的方法

    我们经常会遇到到需要实现底部固定控件的界面,比如详情页,下面就罗列5个常用的方法 方法1:全局增加一个负值下边距等...

  • CSS多种方法实现页面底部固定

    当我们在写页面时经常会遇到页面内容少的时候,footer会戳在页面中间或什么?反正就是不在最底部显示,反正就是很难...

  • CSS固定底部写法

    写在前面 如果本文对您有所帮助,就请点个关注吧! 一、问题描述 本文主要介绍一个Footer元素如何粘住底部,使其...

  • flex相关

    1、flex实现tab固定底部 tab固定底部一直以来使用fixed进行固定定位,下面是flex实现:

  • 使用css让Footer 保持在页面底部的方法

    使用css让Footer 保持在页面底部的方法 如题这次要讨论的是使用css方法,当然也可以通过js实现需求,虽然...

  • sticky-footer写法(用于fixed布局)

    有人经常问,我每次CSS布局position:fixed的时候,想要底部有个固定的元素类似这样 想要一直固定在底部...

  • 面试相关

    一.实现左侧固定,右侧自适应的方法 基本样式html css 1.使用float+margin-left 实现:左...

  • CSS Footer固定底部处理

    Footer应用场景 自适应内容高度展示在页面最底部 固定于浏览器窗口底部 Footer 自适应内容高度展示在页面...

网友评论

    本文标题:5种实现CSS底部固定的方法

    本文链接:https://www.haomeiwen.com/subject/omdbsltx.html