CSS background

HTMLの背景に色や画像を指定するには、CSSプロパティ「background」を使います。画像をタイルのように繰り返し並べたり、スクロールに追随させることもできます。

スタイルシート属性 background は、背景の色や画像、スクロール方法、開始位置を指定します。

書式

background: color image position repeat attachment
background: linear-gradient(color, color)

属性値

color
背景色を指定する。色は color プロパティ同様に指定するか、次の値の中から指定する。
背景色
説明
transparent 透明色(省略値)
inherit 継承

背景色は background-color プロパティでも指定できる。

image
背景に使用する画像を指定します。
背景画像
意味
none 画像なし(規定値)
url(URL) URLで指定した画像を表示
inherit 継承

ローカルファイルのURLを指定する場合は、次のように指定します。

url(file:///C:/image/back.gif)

背景画像は background-image プロパティでも指定できる。

position
背景の横方向の開始位置を指定します。10%のように割合で指定するか、次の値の中から選びます。
position
意味
left 左端
center 中央
right 右端
top 上端
bottom 下端

背景画像の開始位置は background-position プロパティでも指定できる。

repeat
画像の並べ方を指定します。
背景画像の並べ方
意味
repeat 画像を縦横に並べる(省略値)
repeat-x 画像を横方向にのみ並べる
repeat-y 画像を縦方向にのみ並べる
no-repeat 画像を並べない
inherit 継承

画像の並べ方は background-repeat プロパティでも指定できる。

attachment
画面をスクロールさせたときの背景画像の扱いを指定します。
背景画像のスクロール
意味
scroll 一緒にスクロールする(省略値)
fixed スクロールしない
inherit 継承

画面をスクロールさせたときの背景画像の扱いは background-attachment プロパティでも指定できる。

body {
  background: transparent url(http://www.example.com/image/back.gif) repeat fixed left center;
}

linear-gradient

backgroundプロパティにlinear-gradientを使うと、背景色にグラデーションをつけることができます。

background: linear-gradient(color1, color2);
background: linear-gradient(deg, color1, color2);
deg
グラデーションの方向を指定する。
説明
to top 下(color1)から上(color2)
to bottom 上(color1)から下(color2)
to left 右(color1)から左(color2)
to right 左(color1)から右(color2)
45deg 45度(左下から右上)

背景色を選択すると、このページの背景画像が切り替わる。

background: linear-gradient( , , )

関連記事

参考文献

World Wide Web Consortium (2021) CSS Backgrounds and Borders Module Level 3