フッターを Web ページの下部に配置するにはどうすればよいでしょうか?

StackOverflow https://stackoverflow.com/questions/42294

質問

マークアップの右と左の両方の div をクリアするフッターを備えたシンプルな 2 列レイアウトがあります。私の問題は、すべてのブラウザーでフッターをページの下部に配置できないことです。コンテンツがフッターを押し下げる場合は機能しますが、常にそうであるとは限りません。

アップデート:

Firefox では正常に動作しません。ページ上にフッターをブラウザ ウィンドウの一番下まで押し込むのに十分なコンテンツがない場合、フッターの下に背景色の帯が表示されます。残念ながら、これはページのデフォルトの状態です。

役に立ちましたか?

解決

スティッキーフッターを取得するには:

  1. 持っています <div>class="wrapper" あなたのコンテンツのために。

  2. 前に クロージング </div>wrapper を置きます<div class="push"></div>.

  3. クロージング </div>wrapper を置きます<div class="footer"></div>.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}

他のヒント

CSS vh ユニットを使用してください。

おそらく、スティッキーフッターを扱う最も明白でハック的ではない方法は、新しいメソッドを使用することでしょう。 CSSビューポート単位.

たとえば、次の単純なマークアップを考えてみましょう。

<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

ヘッダーの高さがたとえば 80 ピクセル、フッターの高さが 40 ピクセルの場合、スティッキー フッターを作成できます。 たった一つのルールで コンテンツ div で:

.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
}

つまり:コンテンツ div の高さを次のようにします 少なくとも ビューポートの高さからヘッダーとフッターを合わせた高さを引いた 100%。

それでおしまい。

* {
    margin:0;
    padding:0;
}
header {
    background: yellow;
    height: 80px;
}
.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
    background: pink;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

...同じコードが content div 内の多くのコンテンツでどのように動作するかは次のとおりです。

* {
    margin:0;
    padding:0;
}
header {
    background: yellow;
    height: 80px;
}
.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
    background: pink;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
</div>
<footer>
    This is my footer
</footer>

注意:

1) ヘッダーとフッターの高さがわかっている必要があります

2) 古いバージョンの IE (IE8-) および Android (4.4-) はビューポート単位をサポートしていません。(使ってもいいですか)

3) かつて、Webkit には計算ルール内のビューポート単位に問題がありました。これは確かに修正されました (ここを参照してください)なので問題ありません。ただし、何らかの理由で calc の使用を避けたい場合は、負のマージンとボックス サイズのパディングを使用して回避できます。

そのようです:

* {
    margin:0;padding:0;
}
header {
    background: yellow;
    height: 80px;
    position:relative;
}
.content {
    min-height: 100vh;
    background: pink;
    margin: -80px 0 -40px;
    padding: 80px 0 40px;
    box-sizing:border-box;
}
footer {
    height: 40px;
    background: aqua;
}
<header>header goes here</header>
<div class="content">Lorem ipsum 
</div>
<footer>
    This is my footer
</footer>

スティッキーフッター付き display: flex

からインスピレーションを得たソリューション フィリップ・ウォルトンのスティッキー・フッター.

説明

この解決策は、 にのみ有効です:

  • クロム ≥ 21.0
  • Firefox ≥ 20.0
  • Internet Explorer ≥ 10
  • サファリ ≥ 6.1

に基づいています。 flex 画面, を活用して、 flex-grow プロパティ。要素に次のことを許可します。 育つ どちらかで 身長 または (そのとき flow-direction どちらかに設定されます column または row それぞれ)、コンテナ内の余分なスペースを占有します。

も活用していきます。 vh ユニット、ここで 1vhとして定義される:

ビューポートの高さの 1/100

したがって、高さは 100vh これは、要素がビューポートの高さ全体に広がるように指示する簡潔な方法です。

Web ページは次のように構成されます。

----------- body -----------
----------------------------

---------- footer ----------
----------------------------

フッターをページの下部に固定するには、本文とフッターの間のスペースを、フッターをページの下部に押し込むのに必要な分だけ大きくする必要があります。

したがって、レイアウトは次のようになります。

----------- body -----------
----------------------------

---------- spacer ----------
                             <- This element must grow in height
----------------------------

---------- footer ----------
----------------------------

実装

body {
    margin: 0;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.spacer {
    flex: 1;
}

/* make it visible for the purposes of demo */
.footer {
    height: 50px;
    background-color: red;
}
<body>
    <div class="content">Hello World!</div>
    <div class="spacer"></div>
    <footer class="footer"></footer>
</body>

で遊ぶことができます JSフィドル.

サファリの癖

Safari には の欠陥のある実装 flex-shrink 財産, これにより、コンテンツを表示するために必要な最小の高さよりもアイテムを縮小できます。この問題を解決するには、 flex-shrink プロパティを明示的に 0 に設定し、 .content そしてその footer 上の例では:

.content { flex-shrink: 0; }
.footer  { flex-shrink: 0; }

使用できます position: absolute 次のようにページの下部にフッターを配置しますが、2 つの列に適切な値が含まれていることを確認してください。 margin-bottom フッターに隠れないようにします。

#footer {
    position: absolute;
    bottom: 0px;
    width: 100%;
}
#content, #sidebar { 
    margin-bottom: 5em; 
}

ここでは、魅力的に機能する jQuery を使用したソリューションを紹介します。ウィンドウの高さが本体の高さより大きいかどうかをチェックします。そうである場合は、フッターのマージン上部を変更して補正します。Firefox、Chrome、Safari、Opera でテスト済み。

$( function () {

    var height_diff = $( window ).height() - $( 'body' ).height();
    if ( height_diff > 0 ) {
        $( '#footer' ).css( 'margin-top', height_diff );
    }

});

フッターにすでにマージントップ (たとえば 50 ピクセル) がある場合は、最後の部分を次のように変更する必要があります。

css( 'margin-top', height_diff + 50 )

の CSS を設定します。 #footer に:

position: absolute;
bottom: 0;

次に、 padding または margin あなたの底まで #sidebar そして #content の高さに合わせて #footer またはそれらが重なると、 #footer それらをカバーします。

また、私の記憶が正しければ、IE6 には次の問題があります。 bottom: 0 CSS。IE6 用の JS ソリューションを使用する必要がある場合があります (IE6 を重視する場合)。

同様の解決策 @gcedo ただし、フッターを押し下げるために中間コンテンツを追加する必要はありません。単純に追加できます margin-top:auto フッターに追加すると、ユーザーの高さや上のコンテンツの高さに関係なく、ページの下部にプッシュされます。

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  margin:0;
}

.content {
  padding: 50px;
  background: red;
}

.footer {
  margin-top: auto;
  padding:10px;
  background: green;
}
<div class="content">
  some content here
</div>
<footer class="footer">
  some content
</footer>

次の手順に従って、絶対位置と Z インデックスを使用して任意の解像度でスティッキー フッター div を作成します。

  • フッター div を作成します position: absolute; bottom: 0; そして希望の高さ
  • フッターのパディングを設定して、コンテンツの下部とウィンドウの下部の間に空白を追加します。
  • コンテナを作成する div 本文の内容をラップする position: relative; min-height: 100%;
  • メインコンテンツに下部パディングを追加する div これは、フッターの高さにパディングを加えたものに等しい
  • をセットする z-index フッターがコンテナよりも大きい div フッターが切り取られている場合

以下に例を示します。

    <!doctype html>
    <html>
    <head>
      <title>Sticky Footer</title>
      <meta charset="utf-8">
      <style>
      .wrapper { position: relative; min-height: 100%; }
      .footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; }
      .column { height: 2000px; padding-bottom: 300px; background-color: green; }
     /* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */

      </style>
    </head>
    <body>
      <div class="wrapper">
        <div class="column">
          <span>hello</span>
        </div>
        <div class="footer">
          <p>This is a test. This is only a test...</p>
        </div>
      </div>
    </body>
    </html>

コンテンツとサイドバーの周囲にコンテナ div (overflow:auto を使用) を配置してみてください。

それでもうまくいかない場合は、フッターが正しく表示されないスクリーンショットやリンクの例はありますか?

解決策の 1 つは、ボックスの最小高さを設定することです。残念ながらどうやらそうらしい IEでは十分にサポートされていません (驚き)。

これらの純粋な CSS ソリューションはどれも、動的にサイズを変更するコンテンツ (少なくとも Firefox と Safari では) では適切に機能しません。たとえば、コンテナー div、ページに背景を設定し、div 内のテーブルのサイズを変更 (数行追加) した場合、テーブルは、スタイル領域の下部からはみ出すことができます。つまり、フォントの色と背景の色が両方とも白であるため、テーブルの半分を黒のテーマに白にし、テーブルの半分を完全に白にすることができます。基本的に、meroller ページでは修正できません。

ネストされた div の複数列レイアウトは醜いハックであり、フッターを貼り付けるための 100% 最小高さのボディ/コンテナー div はさらに醜いハックです。

私が試したすべてのブラウザで動作する、スクリプトを使用しない唯一のソリューション:thead (ヘッダー用)/tfoot (フッター用)/tbody (任意の数の列の td) と 100% の高さを備えた、より単純で短いテーブル。しかし、これにはセマンティック上および SEO 上の欠点が認識されています (tfoot は tbody より前に出現する必要があります)。ただし、ARIA の役割はまともな検索エンジンに役立つ可能性があります)。

CSS :

  #container{
            width: 100%;
            height: 100vh;
            }
 #container.footer{
            float:left;
            width:100%;
            height:20vh;
            margin-top:80vh;
            background-color:red;
            }

HTML:

           <div id="container">
               <div class="footer">
               </div>
           </div>

これは、常にビューポートの高さの 80% の上マージンを維持する、ページの下部に配置されるレスポンシブなフッターを探している場合にうまくいきます。

この質問について、私が見た答えの多くは不格好で、実装が難しく、非効率的だったので、少し試して、ほんの少しの CSS と HTML を使った独自の解決策を見つけようと思いました。

html,
body {
  height: 100%;
  margin: 0;
}
.body {
  min-height: calc(100% - 2rem);
  width: 100%;
  background-color: grey;
}
.footer {
  height: 2rem;
  width: 100%;
  background-color: yellow;
}
<body>
  <div class="body">test as body</div>
  <div class="footer">test as footer</div>
</body>

これは、フッターの高さを設定し、CSS calc を使用して、フッターが下部にある状態でページの最小の高さを計算することで機能します。これが一部の人々に役立つことを願っています:)

私自身もこれに時々苦労しましたが、すべての div が相互に存在する場合の解決策は厄介な解決策であることが常にわかりました。私はそれを少しいじってみたところ、これが機能することが個人的にわかりました。これは確かに最も簡単な方法の 1 つです。

html {
    position: relative;
}

html, body {
    margin: 0;
    padding: 0;
    min-height: 100%;
}

footer {
    position: absolute;
    bottom: 0;
}

これの気に入っている点は、追加の HTML を適用する必要がないことです。この CSS を追加するだけで、いつでも HTML を書くことができます。

この単純な問題に対する答えは複数の人がここにまとめていますが、何が間違っていたのかを理解するまで私がどれだけイライラしていたかを考えると、付け加えておきたいことが 1 つあります。

前述したように、これを行う最も簡単な方法は次のようになります。

html {
    position: relative;
    min-height: 100%;
}

body {
    background-color: transparent;
    position: static;
    height: 100%;
    margin-bottom: 30px;
}

.site-footer {
    position: absolute;
    height: 30px;
    bottom: 0px;
    left: 0px;
    right: 0px;
}

ただし、おそらく通常はデフォルトであるため、投稿で言及されていないプロパティは、 位置:静的 ボディタグにあります。位置相対は機能しません。

私のWordPressテーマはデフォルトの本文表示を上書きしており、不快なほど長い間私を混乱させました。

私が知っている古いスレッドですが、応答性の高いソリューションを探している場合は、この jQuery の追加が役に立ちます。

$(window).on('resize',sticky);
$(document).bind("ready", function() {
   sticky();
});

function sticky() {
   var fh = $("footer").outerHeight();
   $("#push").css({'height': fh});
   $("#wrapper").css({'margin-bottom': -fh});
}

完全なガイドは次の場所にあります。 https://pixeldesigns.co.uk/blog/owned-jquery-sticky-footer/

非常に単純なライブラリを作成しました https://github.com/ravinderpayal/FooterJS

使い方はとても簡単です。ライブラリをインクルードした後は、このコード行を呼び出すだけです。

footer.init(document.getElementById("ID_OF_ELEMENT_CONTAINING_FOOTER"));

フッターは、異なるパラメータ/ID で上記の関数を呼び出すことで動的に変更できます。

footer.init(document.getElementById("ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER"));

注:- CSS を変更したり追加したりする必要はありません。ライブラリは動的であるため、ページの読み込み後に画面のサイズが変更された場合でも、フッターの位置はリセットされます。CSS でしばらくは解決しましたが、デスクトップからタブレットへ、またはその逆にディスプレイのサイズが大きく変わると、コンテンツに重なったり、粘着性がなくなったりするため、このライブラリを作成しました。

もう 1 つの解決策は CSS メディア クエリです。ただし、このライブラリは自動的に動作し、すべての基本的な JavaScript サポート ブラウザでサポートされている一方で、画面のサイズに応じて異なる CSS スタイルを手動で記述する必要があります。

編集CSS ソリューション:

@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/
    /* For mobile phones: */
    #footer {
        width: 100%;
        position:fixed;
        bottom:0;
    }
}

ここで、表示の高さがコンテンツの長さよりも大きい場合、フッターは下部に固定されます。そうでない場合は、スクロールして表示する必要があるため、フッターは自動的に表示の最後に表示されます。

そして、これは JavaScript/ライブラリよりも優れたソリューションであると思われます。

以前はこのページで提案されている解決策を試してもうまくいきませんでしたが、最終的にこの小さなトリックがうまくいきました。別の可能な解決策として含めます。

footer {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}

フレックスボックスソリューション

ヘッダーとフッターの高さを自然にするには、フレックス レイアウトが推奨されます。このフレックス ソリューションは最新のブラウザでテストされており、実際に IE11 で動作します:)。

「JS フィドル」を参照.

HTML

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  

CSS

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  margin: 0;
  display: flex;
  flex-direction: column;
}

main {
  flex-grow: 1;
  flex-shrink: 0;
}

header,
footer {
  flex: none;
}

私にとって、フッターを表示する最も良い方法は、コンテンツを常に覆わずに下部に固定することです。

#my_footer {
    position: static
    fixed; bottom: 0
}

jQuery クロス ブラウザ カスタム プラグイン - $.footerBottom()

または、私と同じように jQuery を使用し、フッターの高さを次のように設定します。 auto またはへ fix, 、好きなものを選んでも、とにかく機能します。このプラグインは jQuery セレクターを使用するため、機能させるには、ファイルに jQuery ライブラリを含める必要があります。

プラグインを実行する方法は次のとおりです。jQuery をインポートし、このカスタム jQuery プラグインのコードをコピーし、jQuery をインポートした後にインポートします。とてもシンプルで基本的なことですが、重要です。

これを行う場合は、次のコードを実行するだけです。

$.footerBottom({target:"footer"}); //as html5 tag <footer>.
// You can change it to your preferred "div" with for example class "footer" 
// by setting target to {target:"div.footer"}

ドキュメント準備完了イベント内に配置する必要はありません。このままでもちゃんと走りますよ。ページが読み込まれたとき、およびウィンドウのサイズが変更されたときに、フッターの位置が再計算されます。

ここにプラグインのコードがありますが、理解する必要はありません。それを実装する方法を知っておくだけです。それはあなたのために仕事をしてくれます。ただし、それがどのように機能するかを知りたい場合は、コードに目を通してください。あなたのためにコメントを残しました。

//import jQuery library before this script

// Import jQuery library before this script

// Our custom jQuery Plugin
(function($) {
  $.footerBottom = function(options) { // Or use "$.fn.footerBottom" or "$.footerBottom" to call it globally directly from $.footerBottom();
    var defaults = {
      target: "footer",
      container: "html",
      innercontainer: "body",
      css: {
        footer: {
          position: "absolute",
          left: 0,
          bottom: 0,
        },

        html: {
          position: "relative",
          minHeight: "100%"
        }
      }
    };

    options = $.extend(defaults, options);

    // JUST SET SOME CSS DEFINED IN THE DEFAULTS SETTINGS ABOVE
    $(options.target).css({
      "position": options.css.footer.position,
      "left": options.css.footer.left,
      "bottom": options.css.footer.bottom,
    });

    $(options.container).css({
      "position": options.css.html.position,
      "min-height": options.css.html.minHeight,
    });

    function logic() {
      var footerOuterHeight = $(options.target).outerHeight(); // Get outer footer height
      $(options.innercontainer).css('padding-bottom', footerOuterHeight + "px"); // Set padding equal to footer height on body element
      $(options.target).css('height', footerOuterHeight + "!important"); // Set outerHeight of footer element to ... footer
      console.log("jQ custom plugin footerBottom runs"); // Display text in console so ou can check that it works in your browser. Delete it if you like.
    };

    // DEFINE WHEN TO RUN FUNCTION
    $(window).on('load resize', function() { // Run on page loaded and on window resized
      logic();
    });

    // RETURN OBJECT FOR CHAINING IF NEEDED - IF NOT DELETE
    // return this.each(function() {
    //   this.checked = true;
    // });
    // return this;
  };
})(jQuery); // End of plugin


// USE EXAMPLE
$.footerBottom(); // Run our plugin with all default settings for HTML5
/* Set your footer CSS to what ever you like it will work anyway */
footer {
  box-sizing: border-box;
  height: auto;
  width: 100%;
  padding: 30px 0;
  background-color: black;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- The structure doesn't matter much, you will always have html and body tag, so just make sure to point to your footer as needed if you use html5, as it should just do nothing run plugin with no settings it will work by default with the <footer> html5 tag -->
<body>
  <div class="content">
  <header>
    <nav>
      <ul>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
        <li>link</li>
      </ul>
    </nav>
  </header>

  <section>
      <p></p>
      <p>Lorem ipsum...</p>
    </section>
  </div>
  <footer>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
    <p>Copyright 2009 Your name</p>
  </footer>

フレックス ソリューションは、フッターをスティッキーにすることに関してはうまくいきましたが、残念ながら、フレックス レイアウトを使用するように本文を変更すると、ページ レイアウトの一部が変更され、改善にはなりませんでした。最終的に私にとってうまくいったのは次のとおりです。

    jQuery(document).ready(function() {

    var fht = jQuery('footer').outerHeight(true);
    jQuery('main').css('min-height', "calc(92vh - " + fht + "px)");

});

私はこれをctf0の応答から得ました。 https://css-tricks.com/couple-takes-sticky-footer/

以来、 グリッド 解決策はまだ提示されていませんが、ここでは 2 つだけ説明します。 宣言 のために 親要素, 、仮に、 height: 100% そして margin: 0 当然のこと:

html, body {height: 100%}

body {
  display: grid; /* generates a block-level grid */
  align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */
  margin: 0;
}

.content {
  background: lightgreen;
  /* demo / for default snippet window */
  height: 1em;
  animation: height 2.5s linear alternate infinite;
}

footer {background: lightblue}

@keyframes height {to {height: 250px}}
<div class="content">Content</div>
<footer>Footer</footer>

アイテムは、交差軸に沿ってアライメントコンテナ内に均等に分布しています。隣接するアイテムの各ペア間の間隔は同じです。最初のアイテムはメインスタートエッジとフラッシュされ、最後のアイテムはメインエンドのエッジとフラッシュされます。

      div.fixed {
        position: fixed;
        bottom: 0;
        right: 0;
        width: 100%;
        border: 3px solid #73AD21;
      }
  <body style="height:1500px">

    <h2>position: fixed;</h2>

    <p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>

    <div class="fixed">
      This div element has position: fixed;
    </div>

  </body>

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top