[CSS] footer要素下部固定する方法

1 min read
hiroweb developer

コンテンツ部分の高さがウィンドウサイズよりも小さくてフッターが浮いてしまう問題。

これまでの方法

レガシーブラウザにも対応するなら、「Sticky Footer Template for Bootstrap」でも紹介されているような手法を使わざるを得ない。

コードは以下の様な感じ。

html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

ビューポートを使う

<main></main>
<footer></footer>
例えば上記の様な並びだった場合は、以下のようにすれば良い。
main {
  min-height: 100vh;
}

vhビューポートの高さに対する割合を設定できる。
これでコンテンツ要素が小さくても確実に高さが担保できる。綺麗に調整したい場合は、calc(100vh - フッターの高さ)などする必要がある(margin も考慮する必要あり)。

IE9 から対応なのでそこそこのモダンブラウザであれば使うことができる。