概要
ヘッダーとフッターをいい感じに表示するための方法を忘れないようにメモっとく。
この記事に書いてある通りに上から順番に設定していけばOK。
Step0 下準備
パーツを用意する。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="header">
<div>HEADER</div>
</div>
<div class="main">
<div class="contents">
<div>CONTENTS</div>
</div>
</div>
<div class="footer">
<div>FOOTER</div>
</div>
</div>
</body>
</html>
<style>
* {
padding: 0;
margin: 0;
}
.header {
background-color: #d55222;
height: 80px;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.contents {
background-color: #de20d5;
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.footer {
background-color: #29c1e0;
height: 80px;
display: flex;
justify-content: center;
align-items: center;
}
</style>
Step1 ヘッダーを上部に固定する
position: sticky
を利用する。header
クラスにこちらの2行を追加。これで、コンテンツが高くなってスクロールが必要になってもヘッダーは上部に固定されているはず。動作確認したい場合はcontents
クラスのheight
を変更してみるとよい。
.header {
background-color: #d55222;
height: 80px;
color: white;
display: flex;
justify-content: center;
align-items: center;
+ position: sticky;
+ top: 0;
}
Step2 フッターが下部に配置されるようにする
現状、コンテンツの高さが短いと下部に余白ができている。コンテンツが短い場合でもフッターが下部に表示されるようにする。
まずはcontainer
クラスにこちらの3行を適用する。
+ .container {
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ }
次に、main
クラスにflex: 1
を適用する。これでフッターが下部に表示されるようになった。
+ .main {
+ flex: 1;
+ }
これで完成。こんな感じになる。コンテンツの高さが増えた場合は、スクロール終端でフッターが表示される挙動になる。
完成したコード
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="header">
<div>HEADER</div>
</div>
<div class="main">
<div class="contents">
<div>CONTENTS</div>
</div>
</div>
<div class="footer">
<div>FOOTER</div>
</div>
</div>
</body>
</html>
<style>
* {
padding: 0;
margin: 0;
}
.header {
background-color: #d55222;
height: 80px;
color: white;
display: flex;
justify-content: center;
align-items: center;
position: sticky;
top: 0;
}
.container {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.main {
flex: 1;
}
.contents {
background-color: #de20d5;
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.footer {
background-color: #29c1e0;
height: 80px;
display: flex;
justify-content: center;
align-items: center;
}
</style>