はじめに
今回はCSSでWebページ制作における背景画像の設定方法と端末ごとに表示する画像を変える方法について説明します.
Webページの背景画像の設定方法
HTMLファイル及びCSSファイルに以下のコードを記述します.
main.html
<!--背景変更,headタグ内に記述-->
<link rel="stylesheet" href="common/css/sample.css" type="text/css">
sample.css
body {
background-image: url("./images/bg1.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center center;
background-size: cover;
}
各設定の説明
- background-repeat:背景画像の繰り返し(repeatで繰り返し)
- background-attachment:背景画像の固定・移動(scrollで移動)
- background-position:背景画像の表示開始位置
- background-size:背景画像のサイズ(自動的にサイズを合わせる)
他にもいろいろな設定が可能です.参考
端末ごとに表示する背景画像を変更
CSSファイルにて端末のサイズ(幅)ごとに表示画像を変更するコードを記述する.スマホは980px以下,PCは981px以上で設定をしています.
sample.css
@media only screen and (max-width:980px) {
body {
background-image: url("./images/bg1.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center center;
background-size: cover;
}
}
@media only screen and (min-width:981px) {
body {
background-image: url("./images/bg2.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center center;
background-size: cover;
}
}
おまけ
今回のように端末のサイズを調整し確認することを繰り返すなど,頻繁に繰り返していると,Webサイトへの反映がなかなかされない場合があります.そうなった場合はブラウザのキャッシュが原因の可能性が高いです.
キャッシュが残っていると,自動的に以前閲覧した,変更前のWebページを表示してしまいます.これを解決するには,キャッシュのクリアを行えばいいです.スマホなどの場合は履歴を消せば解決します.