Sticky footers,元素一直在頁面底部

小山芋發表於2018-01-17

在網頁設計中,Sticky footers設計是最古老和最常見的效果之一,大多數人都曾經經歷過。它可以概括如下:如果頁面內容不夠長的時候,頁尾塊貼上在視窗底部;如果內容足夠長時,頁尾塊會被內容向下推送。

方法一 :fixed

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sticky footer</title>
<style type="text/css">
*{padding: 0;margin: 0;font-size: 48px}
/* 第一步設定盒子為滿屏大小 */
.box{
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
overflow: auto;
background: green;
}
/* 第二步子盒子設定最小高度且清除浮動 給一個padding-bottom 等於footer 避免內容被footer遮蓋*/
.box .main{
width: 100%;
min-height: 100%;  

padding-bottom: 100px;
}
.box .main .content{
background: orange;
/*padding-bottom: 100px;*/
}
/* 第三步footer的高度和margin-top要相等 */
.box .footer{
position: relative;
width: 100%;
height: 100px;
background: #f3f3f3;
margin: -100px auto 0 auto;
clear: both;
text-align: center;
line-height: 100px;

}
.clearfix{
display: inline-block;

}
.clearfix::after{
content: ".";
display: block;
height: 0;
line-height: 0;
visibility: hidden;
clear: both;
}
</style>
</head>
<body>
<div class="box">
<div class="main clearfix">
<div class="content">
<p>這裡是內容區域</p>
<p>這裡是內容區域</p>
<p>這裡是內容區域</p>
<p>這裡是內容區域</p>
<p>這裡是內容區域</p>
<p>這裡是內容區域</p>
<p>這裡是內容區域</p> 
</div>
</div>
<div class="footer">這是footer區域</div>
</div>
</body>
</html>
複製程式碼

方法二,flexbox

<html>
<head>
<style>
    body { 
        display: flex; flex-flow: column; min-height: 100vh;
    }
    main{flex:1}
    header,footer{height:80px;}
</style>
</head>
<body>
<header> 
   <h1>Site name</h1>
</header> 
<main> 
  <p>Bacon Ipsum dolor sit amet... <!-- Filler text from baconipsum.com -->
  </p>
</main>
<footer> 
  <p> © 2015 No rights reserved.</p> <p>Made with ♥ by an anonymous pastafarian.</p> 
</footer>
</body>
</html>
複製程式碼

我們需要在頁頭和頁尾設定高度,但其內容的高度自動伸縮的來適配剩餘空間。我們可以在main上設定flex值大於0(常用的是1)。
flex屬性是flex-grow、flex-shrink和flex-basis三個屬性縮寫。
任何元素設定了flex大於0,元素就會靈活的控制自己的尺寸,來適配容器的剩餘空間。
例如,如果main設定了flex:2,footer設定了flex:1,那麼頁尾的高度是主內容高度的二分之一,同樣的,如果值設定的是4和2而不是2和1,他們效果是一樣的,因為他們的倍數比例值一樣。

相關文章