內容不超過屏幕,footer固定在底部,超過時被撐出屏幕。
思路(推薦結合代碼一起看,再動手):
1.主內容由.wrap包裹,設置最小高度為100%,是為了讓.main的內容不超出屏幕時,footer可以固定在底部;設置高度auto,是為了當高度超過100%時,可以被.main撐開。
2.給footer設置margin-top:-80px;可以讓footer保持在.wrap的底部,但不超出.wrap(80px是footer的高度)。
3.給.main設置padding-bottom:80px;是因為,當.main的高度超過.wrap高度的100%時,可以讓.main保持在距離.wrap底部80px的地方,正好留個80px的高度給footer(80px是footer的高度)。
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>內容不超過屏幕,footer固定在底部,超過時被撐出屏幕</title> 6 <style type="text/css"> 7 * { 8 margin: 0; 9 padding: 0; 10 } 11 12 html, body { 13 height: 100%; 14 } 15 16 body { 17 font: 14px/1.8 arial; 18 } 19 20 .wrap { 21 height: auto; 22 min-height: 100%; 23 background: #ede1e2; 24 color: #333; 25 font-size: 18px; 26 text-align: center; 27 } 28 29 .main { 30 padding-bottom: 80px; 31 } 32 33 .btn-addSomething { 34 position: fixed; 35 right: 30%; 36 top: 20px; 37 } 38 39 footer { 40 height: 80px; 41 line-height: 80px; 42 margin-top: -80px; 43 background: #333; 44 color: #fff; 45 font-size: 16px; 46 text-align: center; 47 } 48 </style> 49 </head> 50 <body> 51 <section class="wrap"> 52 <div id="main" class="main"> 53 <div id="content"> 54 <h1>標題</h1> 55 <p>我是內容。</p> 56 <p>是的,</p> 57 <p>我真的是內容。</p> 58 <p>我不是內容?</p> 59 <p>我是。</p> 60 <br /> 61 <p>我沒超過屏幕高度時,footer會老實待在固定在底部</p> 62 <p>當我超過屏幕高度時,footer會被我撐出屏幕,但始終在我下面。</p> 63 <p>是的,沒錯,就是這樣。</p> 64 <br /> 65 </div> 66 </div> 67 </section> 68 69 <!-- 添加主內容的按鈕 --> 70 <section class="btn-addSomething"> 71 <button id="btn">點我添加內容</button> 72 </section> 73 74 <footer> 75 <h1>我是footer</h1> 76 </footer> 77 78 <script type="text/javascript"> 79 window.onload = function(){ 80 var content = document.getElementById('content'), 81 main = document.getElementById('main'), 82 btn = document.getElementById('btn'); 83 84 btn.onclick = function(){ 85 var cNode = content.cloneNode(true); 86 main.appendChild(cNode); 87 } 88 } 89 </script> 90 </body> 91 </html>