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 佈局很奇妙吧)
相關文章
相關標籤/搜索