Jiro Laboratory

C#、ASP.NET、JavaScript、Androidとか

ASP.NET MVC + Bootstrap フッタ固定

概要

ブラウザの一番下にフッタを固定で表示させる方法です。
「一番下に固定」といっても微妙に動きの違う方法がいくつかありますのでパターン別に記載します。
ASP.NET MVC5 の新規プロジェクトで作成されるページからカスタマイズする方法として書きます。

その1:縦スクロール時はフッタも一緒にスクロールさせる場合

  • ウィンドウの高さよりコンテンツの高さが小さい場合は、ヘッダはウィンドウ最下部に固定
  • ウィンドウの高さよりコンテンツの高さが大きい場合は、コンテンツと同様にスクロール対象

という動作になります。
DEMOページ

Site.css

html {
  position: relative;
  min-height: 100%;
}
body {
  /* フッタと同じ高さに設定 */
  margin-bottom: 60px;

  /* 一番下までスクロールした時の余白 */
  padding-bottom: 0;
}
.footer {
  position: absolute;
  bottom: 0;
  margin-bottom: 0;
  width: 100%;

  /* フッタの高さ */
  height: 60px;
}
_Layout.cshtml

<body>
  <div class="navbar navbar-fixed-top">
    <div class="container">
    </div>
  </div>

  <div class="container body-content">
    @RenderBody()
  </div>

  <div class="footer">
    <div class="container">
    </div>
  </div> 
</body>
表示イメージ



その2:縦スクロール時もフッタは固定したい場合

その1とは異なり、コンテンツの高さに関係なく、ヘッダは常に最下部に固定されます。
DEMOページ

Site.css

html {
  position: relative;
  min-height: 100%;
}
body {
  /* フッタと同じ高さに設定 */
  margin-bottom: 60px;

  /* 一番下までスクロールした時の余白 */
  padding-bottom: 0;
}
.footer {
  position: fixed;
  bottom: 0;
  margin-bottom: 0;
  width: 100%;

  /* フッタの高さ */
  height: 60px;
}
_Layout.cshtml

<body>
  <div class="navbar navbar-fixed-top">
    <div class="container">
    </div>
  </div>

  <div class="container body-content">
    @RenderBody()
  </div>

  <div class="footer">
    <div class="container">
    </div>
  </div> 
</body>
表示イメージ


前者との違いは

.footer {
  position: fixed;
}

の箇所。

その3:内部コンテンツの高さを100%(wrapスクロール)

こちらは内部コンテンツの高さを100%*1にすることにより、ヘッダを最下部に固定する方法。

DEMOページ

body-content をheight:100%のwrapで囲み、overflow:autoにして、wrap内で縦スクロールさせます。

Site.css

html {
  position: relative;
  height: 100%;
}
body {
  height: 100%;
  padding-bottom: 60px;
}
#wrap {
  height: 100%;
  overflow: auto;
}
.body-content {
  min-height: 100%;
}
.footer {
  position: fixed;
  bottom: 0;
  margin-bottom: 0;
  width: 100%;

  /* フッタの高さ */
  height: 60px;
}
_Layout.cshtml

<body>
  <div class="navbar navbar-fixed-top">
    <div class="container">
    </div>
  </div>

  <div id="wrap">
    <div class="container body-content">
      @RenderBody()
    </div>
  </div

  <div class="footer">
    <div class="container">
    </div>
  </div> 
</body>
表示イメージ



その4:内部コンテンツの高さを100%(bodyスクロール)

こちらの場合、縦スクロールバーはウィンドウと同じ高さになります。
DEMOページ

Site.css

html {
  position: relative;
  height: 100%;
}
body {
  height: 100%;
  padding-bottom: 60px;
}
.body-content {
  min-height: 100%; 
  margin-bottom: 60px;
}
.footer {
  position: fixed;
  bottom: 0;
  margin-bottom: 0;
  width: 100%;

  /* フッタの高さ */
  height: 60px;
}
_Layout.cshtml

<body>
  <div class="navbar navbar-fixed-top">
    <div class="container">
    </div>
  </div>

  <div class="container body-content">
    @RenderBody()
  </div>

  <div class="footer">
    <div class="container">
    </div>
  </div> 
</body>
表示イメージ



*1:実際にはヘッダとフッタの高さを引いた高さになります