次のページ (deadlink: http://www.workingstorage.com/Sample.htm
) には、ページの下部に配置できないフッターがあります。
フッターに
- ページが短く画面がいっぱいにならない場合はウィンドウの下部に固定し、
- 画面いっぱいのコンテンツを超える場合は、ドキュメントの末尾に留まり、通常どおり下に移動します (コンテンツが重なるのではなく)。
CSS が継承されていて、困惑しています。コンテンツに最小の高さを設定したり、フッターを一番下に移動したりするために適切に変更することができないようです。
ベストアンサー1
以下に私の 4 つの異なる方法を示します。
それぞれの例では、テキストを自由に編集して、さまざまなシナリオでコンテンツがどのようにレンダリングされるかを示します。
1) フレックスボックス
body {
min-height: 100vh;
margin: 0;
}
header {
min-height: 50px;
background: lightcyan;
}
footer {
min-height: 50px;
background: PapayaWhip;
}
/* The article fills all the space between header & footer */
body {
display: flex;
flex-direction: column;
}
main {
flex: 1;
}
<header contentEditable>Header</header>
<main contentEditable>Content</main>
<footer contentEditable>Footer</footer>
2) グリッド
最小限の制限で最大限の制御を可能にするため、これが最善の解決策だと思います。
body {
min-height: 100vh;
margin: 0;
display: grid;
grid-template-rows: auto 1fr auto;
}
header {
min-height: 50px;
background: lightcyan;
}
footer {
min-height: 50px;
background: PapayaWhip;
}
<header contentEditable>Header</header>
<main contentEditable>Content</main>
<footer contentEditable>Footer</footer>
3) position:absolute
(動的なフッターの高さなし)
以下の方法では、::after
疑似要素を に配置し、それをフッターと同じbody
高さに設定するという「トリック」を使用します。これにより、フッターと同じスペースが占有され、フッターがその上に配置されると、フッターが実際にスペースを占有しているように見え、絶対配置による悪影響(たとえば、本文のコンテンツの上に表示される)が排除されます。absolute
body {
min-height: 100vh;
margin: 0;
position: relative;
}
header {
min-height: 50px;
background: lightcyan;
}
footer {
background: PapayaWhip;
}
/* Trick: */
body {
position: relative;
}
body::after {
content: '';
display: block;
height: 50px;
/* Set same as footer's height */
}
footer {
position: absolute;
bottom: 0;
width: 100%;
height: 50px;
}
<header contentEditable>Header</header>
<article contentEditable>Content</article>
<footer contentEditable>Footer</footer>
4) テーブルレイアウト
html{ height:100%; }
body { min-height:100%; margin:0; }
header {
height: 50px;
background: lightcyan;
}
main {
height: 1%;
}
footer {
height: 50px;
background: PapayaWhip;
}
/**** Trick: ****/
body {
display: table;
width: 100%;
}
body > footer {
display: table-row;
}
<body>
<header contentEditable>Header</header>
<main contentEditable>Content</main>
<footer contentEditable>Footer</footer>
</body>
5)Calc()
この解決策は機能しますが、欠点もあります。
- ヘッダーとフッターの高さは CSS 変数のみを使用して設定する必要があるため、コンテンツに合わせて動的な高さを表示することはできません。
- 計算は必ずしも完璧ではない可能性があり、小さなギャップやオーバーフローが発生する可能性があります (スクロールバーが表示される場合があります)。
良い点も悪い点も含めて、考えられるすべての解決策を概説したいので、ここにこれを載せました。
:root {
--header-height: 50px;
--footer-height: 50px;
}
/* minimal reset */
body { margin: 0; }
header {
height: var(--header-height);
background: lightcyan;
}
main {
min-height: calc(100vh - var(--header-height) - var(--footer-height));
}
footer {
height: var(--header-height);
background: PapayaWhip;
}
<header contentEditable>Header</header>
<main contentEditable>Content</main>
<footer contentEditable>Footer</footer>