HTMLの背景に色や画像を指定するには、CSSプロパティ「background」を使います。画像をタイルのように繰り返し並べたり、スクロールに追随させることもできます。
スタイルシート属性 background は、背景の色や画像、スクロール方法、開始位置を指定します。
background: color image position repeat attachment
background: linear-gradient(color, color)
| 値 | 説明 |
|---|---|
| transparent | 透明色(省略値) |
| inherit | 継承 |
body {
background: transparent url(http://www.example.com/image/back.gif) repeat fixed left center;
}
背景色は background-color プロパティでも指定できる。
| 値 | 意味 |
|---|---|
| none | 画像なし(規定値) |
| url(URL) | URLで指定した画像を表示 |
| inherit | 継承 |
ローカルファイルのURLを指定する場合は、次のように指定します。
url(file:///C:/image/back.gif)
背景画像は background-image プロパティでも指定できる。
| 値 | 意味 |
|---|---|
| left | 左端 |
| center | 中央 |
| right | 右端 |
| top | 上端 |
| bottom | 下端 |
背景画像の開始位置は background-position プロパティでも指定できる。
| 値 | 意味 |
|---|---|
| repeat | 画像を縦横に並べる(省略値) |
| repeat-x | 画像を横方向にのみ並べる |
| repeat-y | 画像を縦方向にのみ並べる |
| no-repeat | 画像を並べない |
| inherit | 継承 |
画像の並べ方は background-repeat プロパティでも指定できる。
| 値 | 意味 |
|---|---|
| scroll | 一緒にスクロールする(省略値) |
| fixed | スクロールしない |
| inherit | 継承 |
画面をスクロールさせたときの背景画像の扱いは background-attachment プロパティでも指定できる。
background: linear-gradient(color1, color2);
background: linear-gradient(deg, color1, color2);
| 値 | 説明 |
|---|---|
| to top | 下(color1)から上(color2) |
| to bottom | 上(color1)から下(color2) |
| to left | 右(color1)から左(color2) |
| to right | 左(color1)から右(color2) |
| 45deg | 45度(左下から右上) |
背景色を選択すると、このページの背景画像が切り替わる。
background: linear-gradient( , , )
background: transparent none 0% 0% auto repeat scroll;
background で指定できる各プロパティの初期値を以下に示す。
| プロパティ | 初期値 |
|---|---|
| background-color | transparent |
| background-image | none |
| background-position | 0% 0% |
| background-size | auto |
| background-repeat | repeat |
| background-attachment | scroll |
全ての要素に対して background プロパティを指定できる。
World Wide Web Consortium (2021) CSS Backgrounds and Borders Module Level 3