【CSS】Sticky Footer(スティッキーフッター)の実装
常にページ最下部に固定するようなフッターを実現したい。
このとき、ページ内の要素が画面の高さを越えるときは、フッターは画面外となり、スクロールしなければ表示されないようにしたい。
このようなフッターは「Sticky Footer(スティッキーフッター)」と呼ばれたりする。
コード
CodePenみて。
CodePenそのままのコードも載せておく。
<body> <header> header </header> <div class="main-container"> Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit,<br> sed do eiusmod tempor<br> incididunt ut labore<br> et dolore magna aliqua.<br> Ut enim ad minim veniam,<br> quis nostrud exercitation<br> ullamco laboris nisi ut<br> aliquip ex ea commodo<br> consequat. Duis aute irure<br> dolor in reprehenderit in<br> voluptate velit esse cillum<br> dolore eu fugiat nulla<br> pariatur. Excepteur sint<br> occaecat cupidatat non<br> proident, sunt in culpa qui<br> officia deserunt mollit anim<br> id est laborum.<br> </div> <footer> footer </footer> </body>
/* Sticky footer */ body { min-height: 100vh; display: flex; flex-direction: column; } .main-container { margin-bottom: auto; } /* Setting background color */ header { background-color: red; } .main-container { background-color: green; } footer { background-color: blue; }
解説
body
に display: flex;
と flex-direction: column;
を指定してflexで子要素を上から下に配置する。
また min-height: 100vh;
を指定して常にビューポートいっぱいに高さを確保しておく。
ここで、 flexの子要素はautoマージンを指定すると取れるだけのスペースを占有しようとする 特性を利用する。
具体的には .main-container
に margin-bottom: auto;
を指定することで、下方向の取れるだけのスペースをすべて占有する。
結果として footer
は下方向に押し下げられ、Sticky Footerを実現できる。