div 底部固定方法(不用position定位)

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

<style>
html, body {
  height: 100%;
  margin: 0;
}
.content {
  padding: 20px;
  min-height: 100%;
  margin: 0 auto -50px;
}
.footer,.push {
  height: 50px;
}
</style>
<div class="content">
  <h1>Sticky Footer with Negative Margin 1</h1>
  <p><button id="add">Add Content</button></p>
  <div class="push"></div>
</div>
<footer class="footer">Footer </footer>

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

<style>
html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}
body {
  font: 16px Sans-Serif;
}
h1 {
  margin: 0 0 20px 0;
}
p {
  margin: 20px 0 0 0;
}
footer {
  background: #42A5F5;
  color: white;
  line-height: 50px;
  padding: 0 20px;
}
</style>
<div class="content">
  <div class="content-inside">
    <h1>Sticky Footer with Negative Margin 2</h1>
    <p><button id="add">Add Content</button></p>
  </div>
</div>
<footer class="footer"> Footer </footer>

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

<style>
.content {
  min-height: calc(100vh - 70px);
  padding: 40px 40px 0 40px;
}
.footer {
  height: 50px;
}
* {
  box-sizing: border-box;
}
body {
  margin: 0;
  font: 16px Sans-Serif;
}
h1 {
  margin: 0 0 20px 0;
}
p {
  margin: 0 0 20px 0;
}
footer {
  background: #42A5F5;
  color: white;
  line-height: 50px;
  padding: 0 20px;
}
</style>
<div class="content">
  <h1>Sticky Footer with calc()</h1>
  <p><button id="add">Add Content</button></p>
</div>
<footer class="footer"> Footer </footer>

方法四:使用flexbox

<style>
html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
  padding: 20px;
}
.footer {
  padding: 20px;
}
</style>
<div class="content">
  <h1>Sticky Footer with Flexbox</h1>
  <p><button id="add">Add Content</button></p>
</div>

<footer class="footer">Footer </footer>

方法五:使用grid布局

<style>
html {
  height: 100%;
}
body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}
.content {
  padding: 20px;
}
.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}
* {
  box-sizing: border-box;
}
body {
  margin: 0;
  font: 16px Sans-Serif;
}
h1 {
  margin: 0 0 20px 0;
}
p {
  margin: 0 0 20px 0;
}
.footer {
  background: #42A5F5;
  color: white;
  padding: 20px;
}
</style>
<div class="content">
  <h1>Sticky Footer with Grid</h1>
  <p><button id="add">Add Content</button></p>
</div>
<footer class="footer">Footer</footer>
    原文作者:夏忆
    原文地址: https://segmentfault.com/a/1190000009200940
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞