CSS ・ 色・背景
background-image
背景画像
要素の背景に画像やグラデーションを表示します。表示位置・大きさ・繰り返しは別のプロパティで調整します。
01
サンプルコード
HTML
1<div class="hero">背景に画像</div>
2<div class="grad">背景にグラデーション</div>
CSS
1.hero, .grad {
2 height: 90px;
3 display: grid;
4 place-items: center;
5 margin-bottom: 8px;
6 color: #fff;
7 font-weight: bold;
8}
9.hero {
10 background-image: url("photo.jpg");
11 background-size: cover;
12 background-position: center;
13 place-items: end start;
14 padding: 8px 12px;
15 color: #5a3b0a;
16}
17.grad {
18 background-image: linear-gradient(90deg, #b68235, #5a3b0a);
19}
02
実行結果
ブラウザでの表示
03
解説
background-image は、url() で画像ファイルを、linear-gradient() などでグラデーションを背景に表示するプロパティです。
既定では画像が元の大きさで繰り返し並びます。background-size: cover で要素全体を覆うように拡大し、background-repeat: no-repeat で繰り返しを止めるのが定番です。
背景画像は装飾として扱われ、読み上げソフトには伝わりません。内容として意味のある画像は img で配置します。
背景色・背景画像・位置・繰り返しなどは background プロパティで1行にまとめても書けます(ショートハンド)。ただし、どの値が何を指しているか読み取りにくく、書かなかった値は初期値に戻るため、background-color・background-image のように別々に書いたほうが分かりやすくなります。
04
応用例・注意点
一緒に使うプロパティ
| プロパティ | 説明 |
|---|---|
background-size | cover(全体を覆う)/ contain(全体を収める) |
background-position | 表示位置(left top・center など) |
background-repeat | 繰り返し(no-repeat で繰り返さない) |
background-attachment | fixed でスクロールしても固定 |
linear-gradient() | 直線状のグラデーション |
画像の上に暗い幕をかけて文字を読みやすくする
背景画像は複数重ねられます。先に書いたものが手前に表示されます。
CSS
1.hero {
2 background-image:
3 linear-gradient(rgb(0 0 0 / 40%), rgb(0 0 0 / 40%)),
4 url("hero.jpg");
5 background-size: cover;
6 color: #fff;
7}
background の一括指定と個別指定
どちらも同じ結果です。個別に書いたほうが、後から一部だけ変更するときに分かりやすくなります。
CSS
1/* 一括指定(ショートハンド) */
2.acthouse {
3 background: #000 url("../images/bg_01.jpg") left top no-repeat;
4}
5
6/* 個別に指定 */
7.acthouse {
8 background-color: #000;
9 background-image: url("../images/bg_01.jpg");
10 background-position: left top;
11 background-repeat: no-repeat;
12}
注意点
- 01url() のパスは、HTMLではなくCSSファイルの場所が基準です。
- 02背景画像の上に文字を載せるときは、どんな画像でも読めるコントラストを確保します。