css sticky footer 布局

方法一:footer 上用负的 margin-top

  • 在内容外面需要额外包一层元素(wrap)来让它产生对应的 padding-bottom。是为了防止负 margin 导致 footer 覆盖任何实际内容。
//html结构
<body>
<div id="wrap">
	<div id="main">
		main<br/>
		main<br/>
	</div>
</div>
<div id="footer"></div>
</body>

//css样式
html, body {
  height: 100%;
  margin: 0;
}
#wrap{
	width: 100%;
    min-height: 100%;
}
/*内容区需要让出一部分区域,防止内容被盖住*/
#main{ padding-bottom: 30px; } //wrap包裹内容的最小高度是100%,此时将footer的部分通过margin-top拉上去30px。 #footer{ width: 100%; height: 30px; background-color: yellow; margin-top: -30px; } 
 

方法二:负margin-bottom

  • 用一个元素将除了 footer 之外的其他内容包起来。给它设一个负的 margin-bottom,让它正好等于 footer 的高度。这是一个最基本的方法。
<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%;
  margin-bottom: -50px;
}
.footer,
.push {
  height: 50px;
}
复制代码
 

方法三:flex布局

  • Web 设计中固定高度通常都不好,内容可能改变,我们需要footer灵活性。固定高度通常要被亮红灯。使用 flexbox 来实现粘连 footer 不仅不需要任何额外的元素,还可以支持 footer 可变高度。
//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;
}
.footer{
	height: 50px;
    background-color: red;
}
复制代码
  • 甚至可以添加一个 header 到 .content 前面或者其他更多内容到后面。使用 flexbox 的诀窍是:
  • 设置 flex: 1 在你希望自动填充窗口空间的子元素上(在我们的例子里是 .content 元素)。
  • 可以设置 margin-top:auto 来让子元素尽可能远离它前面的元素(或者根据需要选择任意一个方向的 margin)。(上面的 flex:1 也可以用 margin-bottom:auto,内容垂直居中可以用margin:auto 0,flex 布局很奇妙吧)

猜你喜欢

转载自www.cnblogs.com/little-ab/p/11084064.html
今日推荐