他のソリューションと比較して、コンテナを追加する必要はありません。したがって、このソリューションはもう少しエレガントです。コード例の下で、これが機能する理由を説明します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
html
{
height:100%;
}
body
{
min-height:100%;
padding:0; /*not needed, but otherwise header and footer tags have padding and margin*/
margin:0; /*see above comment*/
}
body
{
position:relative;
padding-bottom:60px; /* Same height as the footer. */
}
footer
{
position:absolute;
bottom:0px;
height: 60px;
background-color: red;
}
</style>
</head>
<body>
<header>header</header>
<footer>footer</footer>
</body>
</html>
最初に行うことは、最大のコンテナー ( html ) を 100% にすることです。html ページは、ページ自体と同じ大きさです。次に、body の高さを設定します。これは、html タグの 100% よりも大きくすることができますが、少なくとも同じ大きさにする必要があるため、min-height 100% を使用します。
また、身体を相対的にします。相対とは、ブロック要素を元の位置から相対的に移動できることを意味します。ただし、ここでは使用しません。親戚には二次利用があるからです。絶対要素は、ルート (html) または最初の相対親/祖父母に対して絶対的です。それが私たちが望んでいることです。フッターは、本文、つまり下部に対して絶対的なものにしたいと考えています。
最後のステップは、フッターをabsoluteとbottom:0に設定することです。これにより、相対的な最初の親/祖父母の下部に移動します( body ofcourse )。
ページ全体を埋めると、コンテンツがフッターの下に表示されます。なんで?フッターはもはや「html フロー」内にないため、絶対的なものです。では、これを修正するにはどうすればよいでしょうか。ボディに padding-bottom を追加します。これにより、本文がコンテンツよりも実際に大きくなります。