CSS 背景 (Backgrounds)
1. CSS 背景プロパティの概要
CSS 背景プロパティは、要素に対して背景効果を追加するために使用されます。
この記事では、以下の CSS 背景プロパティについて詳しく見ていきます。
background-colorbackground-imagebackground-repeatbackground-attachmentbackground-positionbackground(一括指定プロパティ)
2. CSS background-color
background-color プロパティは、要素の背景色を指定します。
/* ページ全体の背景色を lightblue に設定 */
body {
background-color: lightblue;
}CSS では、色は通常以下の方法で指定されます。
- 有効なカラー名(例:
red) - HEX 値(例:
#ff0000) - RGB 値(例:
rgb(255,0,0))
2.1 他の要素への適用
背景色は、任意の HTML 要素に対して設定することが可能です。
h1 {
background-color: green;
}
div {
background-color: lightblue;
}
p {
background-color: yellow;
}3. CSS background-image
background-image プロパティは、要素の背景として使用する画像を指定します。デフォルトでは、画像は要素全体を覆うように繰り返されます。
/* ページ全体の背景画像を設定 */
body {
background-image: url("paper.gif");
}注意: 背景画像を使用する際は、画像がテキストの読みやすさを損なわないように注意してください。
4. CSS background-repeat
デフォルトでは、background-image プロパティは画像を水平方向と垂直方向の両方に繰り返します。
画像によっては、水平方向または垂直方向のみに繰り返すべき場合があります。さもなければ、以下のように見た目が不自然になることがあります。
body {
background-image: url("gradient_bg.png");
}4.1 水平または垂直方向にのみ繰り返す
画像を水平方向のみに繰り返す場合は、background-repeat: repeat-x; を使用します。
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}垂直方向に繰り返す場合は、repeat-y を指定します。
4.2 背景画像の繰り返しを禁止する
背景画像を一度だけ表示したい場合は、background-repeat プロパティを no-repeat に設定します。
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}5. CSS background-position
background-position プロパティは、背景画像を表示する位置を指定するために使用されます。
/* 画像を右上に配置し、一度だけ表示する */
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}6. CSS background-attachment
background-attachment プロパティは、背景画像をスクロールさせるか、あるいは固定(ページをスクロールしても画像が動かない状態)にするかを指定します。
6.1 背景画像を固定する (fixed)
背景画像がページの他の部分と一緒にスクロールしないようにするには、fixed を指定します。
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}6.2 背景画像をスクロールさせる (scroll)
背景画像がページの残りの部分と一緒にスクロールするようにするには、scroll を指定します。これがデフォルトの挙動です。
body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}7. CSS 背景の一括指定 (Shorthand Property)
コードを短縮するために、すべての背景プロパティを一つのプロパティで指定することも可能です。これは一括指定プロパティ (Shorthand property) と呼ばれます。
複数の個別プロパティを使用する代わりに、background プロパティだけを使用します。
/* 一括指定プロパティの使用例 */
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}一括指定プロパティを使用する場合、値の順序は以下の通りです。
background-colorbackground-imagebackground-repeatbackground-attachmentbackground-position
※プロパティの値が欠けていても、この順序に従っている限り問題ありません。
8. CSS 背景プロパティの一覧
| プロパティ | 内容 |
|---|---|
background | すべての背景プロパティを一つの宣言で設定するためのショートハンド |
background-attachment | 背景画像が固定されるか、ページの他の部分と一緒にスクロールするかを設定 |
background-clip | 背景の描画領域を指定 |
background-color | 要素の背景色を設定 |
background-image | 要素の背景画像を設定 |
background-origin | 背景画像の基準位置を指定 |
background-position | 背景画像の開始位置を設定 |
background-repeat | 背景画像の繰り返し方法を設定 |
background-size | 背景画像のサイズを指定 |