背景を彩る background プロパティ
background プロパティ
backgroundプロパティにより、背景に関するCSSプロパティが一度に設定できます。
一括指定できるプロパティ
・background-clip ・background-color・background-image・background-origin・background-position・background-repeat・background-size ・background-attachment
これらのうち1つが記述されれば有効です。
background-image プロパティ
要素の背景に画像を設置します。
「url」に続いて丸かっこ()内に画像のパスを記述します。CSSファイルからみた画像ファイルの位置を書きます。
body {
background-color:#CCC;
background-image: url(images/bg.png);
}
background-repeat プロパティ
CSSのデフォルト設定では背景画像を縦と横に繰り返し表示し、画面いっぱいに画像を敷き詰めます。
これをどの方向に繰り返すか、または繰り返さないかをbackground-repeatプロパティで設定します。
主な値
指定方法 | 説明 |
---|---|
repeat | 縦、横ともに繰り返して表示 |
repeat-x | 横方向に繰り返して表示 |
repeat-y | 縦方向に繰り返して表示 |
no-repeat | 繰り返さない |
body {
background-image: url(images/bg.png);
background-repeat: repeat-x;
}
background-size プロパティ
背景画像のサイズを指定します。
指定方法には「px」や「rem」、「%」などの数値や「cover」、「contain」といったキーワードで指定する方法があります。
主な値
指定方法 | 説明 |
---|---|
数値 | 数値に「px」や「%」などの単位をつける |
キーワード | 「cover」、「contain」で指定 |
cover
「cover」は画像の縦横比を保持したまま表示領域をうめつくすように背景画像を表示します。
div {
background-image: url(images/bg.png);
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
}
contain
「contain」は画像の縦横比を保持したまま画像が全て表示されるように表示します。表示領域の方が大きい場合は余白ができます。
div {
background-image: url(images/bg.png);
background-repeat: no-repeat;
background-size: contain;
height: 100vh;
}
background-position プロパティ
背景画像の表示開始位置を指定するプロパティです。 背景画像の表示開始位置を%値や数値で指定する場合には、値を横方向・縦方向の順にスペースで区切って指定します。
指定方法 | 説明 |
---|---|
数値 | 数値に「px」や「rem」、「%」などの単位をつける |
キーワード | 横方向は「left(左)」、「center(中央)」、「right(右)」、縦方向は「top(上)」、「center(中央)」、「bottom(下)」 |
body {
background-image: url(image/bg.png);
background-repeat: no-repeat;
background-position: center top;
}