CSSの背景画像の使い方完全ガイド|backgroundプロパティを初心者向けに解説

CSS
Abstract computer script code. Programming code screen of software developer. Software Programming

CSSの背景画像の設置方法について説明していきます。

背景画像の設置方法

以下の様々なプロパティを使用して、背景に画像を設置することが出来ます。

background-image

一番基本となる背景画像の設置方法です。
背景画像が読み込まれないことも考えて、背景画像と同じような色合いの背景色も指定してあげましょう。

  • url:画像ファイルの指定
  • none:背景画像を使用しない

上記のどちらかを指定してあげます。

body{
background-color:red;
background-image:url(images/image.jpg);
}

background-repeat

画面いっぱいに画像を表示させず、どの方向に繰り返す・繰り返さないのかを指定してあげることが出来ます。
background-imageと基本セットで使用します。

  • repeat:縦・横ともに繰り返して表示
  • repeat-x:横方向に繰り返して表示
  • repeat-y:縦方向に繰り返して表示
  • no-repeat:繰り返さない

body{
background-color:red;
background-image:url(images/image.jpg);
background-repeat:repeat-x;
}

background-size

背景画像のサイズを指定します。
元の画像の比率を維持したまま要素に当てはめたり、指定したサイズに引き伸ばしたり出来ます。background-imageと基本セットで使用します。

  • 数値で指定:pxやrem、%などの単位をつける
  • キーワードで指定:cover=要素いっぱいに拡大 , contain=画面全体を表示

coverは画像が画面から見切れてしまうデメリット、contianは画面に余白が出来るデメリットがあります。

body{
background-color:red;
background-image:url(images/image.jpg);
background-repeat:no-repeat;
background-size:cover;
}

background-position

背景画像を表示する位置を指定します。基本的に横方向、縦方向の順番にスペースを区切って記述します。
background-imageと基本セットで使用します。

  • 数値で指定:pxやrem、%などの単位をつける
  • キーワードで指定(横方向):left=左、center=中央、right=右
  • キーワードで指定(縦方向):top=上、center=中央、bottom=下

body{
background-color:red;
background-image:url(images/image.jpg);
background-repeat:no-repeat;
background-position:center top;
}

background-attachment

背景画像の挙動を指定します。
background-imageと基本セットで使用します。

  • scroll(デフォルト):背景は要素にくっつく。ぺージをスクロールすると一緒に動く
  • fixed:背景が画像に固定される。要素ではなく、ビューポートに対して固定される

body{
background-color:red;
background-image:url(images/image.jpg);
background-repeat:no-repeat;
background-attachment:fixed;
}

background(ショートハンド)

backgroundの記述を短く指定してあげることが出来ます。
魔術でいうところの短縮詠唱のようなもので、出来たらかっこいいです。
positionとsizeは「/」で区切ることを忘れえないようにしましょう。

background:url(images/image.jpg)no-repeat center / cover #000;

以下は、上記記述コードの順番となります。記述なしの場合はデフォルトになります。

background:
background-image
background-repeat
background-position / background-size
background-attachment
background-origin
background-clip
background-color;

コメント

タイトルとURLをコピーしました