css经典布局系列四——粘连(css sticky footer)布局

什么是粘连布局(css sticky footer)

  • 当main的高度足够长的时候,紧跟在<\main>后面的元素<\footer>会跟在其后面;css

  • 当<\main>元素比较短的时候(好比小于屏幕的高度),咱们指望这个<\footer>元素可以“粘连”在屏幕的底部。 html

    粘连布局

  • 三个组成部分:wrap容器,main内容,footer脚部bash

方法一: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 布局很奇妙吧)
相关文章
相关标签/搜索