ウィンドウ幅いっぱいに背景画像を表示したい
Webサイトのトップページなどで、ブラウザのウィンドウサイズいっぱいに広がる画像を表示させたいことがあります。実現する方法としては、<div>タグに、大きな背景画像を適用しています。できるだけ大きく画像を表示させるときのポイントとなるのが、background-positionプロパティで指定する背景画像の配置方法です。この値を「center top」にしておくと、ウィンドウの広さにかかわらず画像の中心部分は常に表示されるようになります。
サンプル
このサンプルでは、ウィンドウサイズいっぱいに広がるように「height: 100%」を適用した<div class=”keyvisual”>に背景画像を適用しています。なお、サンプルではbackground-positionプロパティを使わずに、背景の設定を一括でできるbackgroundプロパティを使用しています。
<!DOCTYPE html>
<html lang="ja">
<head>
<title>サンプルページ</title>
<meta charset="uft-8">
<style>
html{
height: 100%;
}
body{
margin:0;
height: 100%;
}
.keyvisual{
position: relative;
height: 100%;
background:url(./images/bigbg.jpg) center top no-repeat;
}
.logo{
position: absolute;
top:50%;
left:50%;
margin-top:-300px;
margin-left:-300px;
}
</style>
</head>
<body>
<div class="keyvisual">
<img class="logo" src="./images/biglogo.png" alt=""/>
</div>
</body>
</html>
実行結果


極端にウィンドウサイズが大きいと埋め尽くせない時の方法
上記の方法だと、常に画像の中心部分を表示するという利点がありますが、その反面、画像自体を伸縮させないため、極端にウィンドウサイズが大きいと埋め尽くせない場合が出てきます。

もし、ウィンドウ全体を背景画像で覆いたいときは、背景画像を適用する要素のスタイルに「background-size: cover;」を追加します。このプロパティがあると、背景画像はボックスの大きさに合わせて伸縮するようになり、常にウィンドウ全体に画像を表示させることができるようになります。
<!DOCTYPE html>
<html lang="ja">
<head>
<title>サンプルページ</title>
<meta charset="uft-8">
<style>
html{
height: 100%;
}
body{
margin:0;
height: 100%;
}
.keyvisual{
position: relative;
height: 100%;
background:url(./images/bigbg.jpg) center top no-repeat;
background-size: cover;
}
.logo{
position: absolute;
top:50%;
left:50%;
margin-top:-300px;
margin-left:-300px;
}
</style>
</head>
<body>
<div class="keyvisual">
<img class="logo" src="./images/biglogo.png" alt=""/>
</div>
</body>
</html>
実行結果
