LoginSignup
26
30

More than 5 years have passed since last update.

固定headerとfooterの間に、過不足なくコンテンツを表示する

Last updated at Posted at 2014-11-29

よくあるチャットアプリっぽい見た目のレイアウトを作ってみたいなー、と思ってやってみたら意外と簡単にできたのでメモ。

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<header>
<h1>へっだー</h1>
</header>
<div id="contents">
</div>
<footer>
<h1>ふったー</h1>
</footer>
</body>
</html>
style.css
*{
  margin:0;
  padding:0;
}
body{
  width:100%;
}
header{
  position:fixed;
  top:0;
  left:0;
  z-index:10;
  width:100%;
  height:50px;
}
#contents{
  padding-top:10px;
  margin-top:50px;
  height:auto;
  padding-bottom:10px;
  margin-bottom:80px;
}
footer{
  position:fixed;
  bottom:0;
  left:0;
  z-index:10;
  width:100%;
  height:80px;
}

ポイントは、#contentspaddingmarginを使って、headerfooterが乗って隠れることになる部分の「糊代」ならぬ「乗り代」を稼いでおくことです。

そのため、#contentsmargin-topheaderheightに、margin-bottomfooterheightに等しい値をとっています。

僕は今回marginを使って乗り代を、paddingを使って要素同士の見かけ上の間隔を取りましたが、逆でも全然OKだと思います。

複雑なページデザインの場合

さて、上記の例は、ページが静的なデザインであり、余計なpaddingmarginも存在しないような場合にはそのまま適用可能ですが、そうでない複雑なページデザインの場合は上手くいかない可能性があります。(実際はこういう場面の方が多いかもしれません)

この場合、JavaScriptを用いて、要素そのもののサイズを取得したり、ページの変化を監視したりといったことが必要になってきます。

main.js
$(function(){
    reviseMargin();
    function reviseMargin(){
        $("#contents").css({
            "margin-top":$("header")[0].offsetHeight + "px",
            "margin-bottom": $("footer")[0].offsetHeight + "px"
        });
    }
});

上記のようなプログラムを用いることで、ページの読み込みが終わった際に各要素のサイズを確認し、marginの値を再設定することができます。
ここで、offsetHeightとは、paddingborderまで含めた要素自体のサイズを示しています。もし、CSSのサイズ指定に%と固定pxが入り交じっているようなレイアウトであっても、pxで値を得ることができます。

HTMLElement.offsetHeight - Web API インターフェイス | MDN

もし、windowサイズの変更にも対応するようにしたいならば、windowresizeイベントにコールバックを設定しておけばOKです。

main.js
$(function(){
    reviseMargin();
    $(window).on("resize",reviseMargin);

    function reviseMargin(){
        $("#contents").css({
            "margin-top":$("header")[0].offsetHeight + "px",
            "margin-bottom": $("footer")[0].offsetHeight + "px"
        });
    }
});

実例

下画像は、LINEアカウント乗っ取り被害により、家族から依頼されて我が家のチャット用にwebsocketで作ったアプリのスクリーンショットです。こんな感じのレイアウトができます。

img3.png

ちなみに、アプリは「やっぱLINEでいっか」という、アカウント作り直した家族の傍若無人な一言でお蔵入りとなりました。世知辛いです。

以上です。何かの参考になれば幸いです。

26
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
30