背景画像を設定する
background-image は、要素の内容、padding、border の後ろに画像を描きます。初期状態では padding ボックスの左上から始まり、画像本来のサイズのまま、ボックスを埋めるように繰り返されます:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Background image</title>
<style>
body { font-family: system-ui, sans-serif; }
.dots {
/* a 24x24 image: one blue dot */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='4' fill='%232563eb'/%3E%3C/svg%3E");
height: 120px;
padding: 16px;
border: 2px solid #111827;
font-weight: 600;
}
</style>
</head>
<body>
<div class="dots">One 24px image, repeated to fill the box</div>
</body>
</html>
実際のプロジェクトでは url() はファイルを指します: url("images/hero.jpg")。パスは、その指定を含むスタイルシートからの相対パスです (<style> 要素ではページからの相対パス)。このページの例は、どこでも動くように、小さな SVG 画像を data: URL としてインラインで書いています。
最初に知っておきたいことが 2 つあります:
- 背景は要素にサイズを与えません。 背景画像を指定した空の
div の高さは 0px です。内容、padding、height、aspect-ratio のどれかで大きさを与えてください。
- 背景画像は装飾です。 スクリーンリーダーは読み飛ばし、代替テキストもありません。意味を持つ画像は
<img> 要素で表示します。
background-size: cover、contain、長さ
background-size は画像の大きさを変えます。2 つのキーワードは縦横比を保ちます:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>cover vs contain</title>
<style>
body { font-family: system-ui, sans-serif; font-size: 14px; }
.row { display: flex; gap: 12px; flex-wrap: wrap; }
.box {
--landscape: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200' viewBox='0 0 400 200'%3E%3Crect width='400' height='200' fill='%23bfdbfe'/%3E%3Ccircle cx='320' cy='50' r='24' fill='%23f59e0b'/%3E%3Cpath d='M0 200L120 70L220 200Z' fill='%2316a34a'/%3E%3Cpath d='M140 200L270 90L400 200Z' fill='%2315803d'/%3E%3C/svg%3E");
width: 160px; height: 160px;
background: var(--landscape) center / auto no-repeat, #e5e7eb;
border: 2px solid #111827;
}
.cover { background-size: cover; }
.contain { background-size: contain; }
.stretch { background-size: 100% 100%; }
</style>
</head>
<body>
<div class="row">
<div><div class="box"></div>auto (400x200, cropped)</div>
<div><div class="box cover"></div>cover</div>
<div><div class="box contain"></div>contain</div>
<div><div class="box stretch"></div>100% 100% (distorted)</div>
</div>
</body>
</html>
画像は横幅が高さの 2 倍で、どのボックスも正方形です。
| 値 | 結果 |
|---|
auto (初期値) | 画像本来のサイズ |
cover | ボックスを完全に埋めるまで拡大縮小し、はみ出た部分は切り取られる |
contain | 画像全体が収まるまで拡大縮小し、2 辺に灰色の帯が残る |
200px | 幅 200px、高さは比率に合わせる |
50% auto | ボックスの幅の半分、高さは比率に合わせる |
100% 100% | ボックスとぴったり同じサイズ。縦横比が違うと画像がゆがむ |
ヒーローバナーやカードには cover がよく使われます。contain は、絶対に切れてはいけないロゴやイラストに使います。
background-position と background-repeat
background-position はボックスの中の画像の位置を、キーワード (top、center、bottom、left、right)、パーセント、長さで指定します。background-repeat は繰り返しを制御します。いろいろな値を試してみてください:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Position and repeat</title>
<style>
body { font-family: system-ui, sans-serif; }
#box {
height: 140px; margin-top: 10px;
border: 2px solid #111827;
background-color: #f3f4f6;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='4' fill='%232563eb'/%3E%3C/svg%3E");
background-size: 48px;
}
label { display: block; margin-top: 6px; }
</style>
</head>
<body>
<label>background-position: <input id="pos" value="center" size="18"></label>
<label>background-repeat: <input id="rep" value="no-repeat" size="18"></label>
<div id="box"></div>
<script>
const box = document.getElementById('box');
const pos = document.getElementById('pos');
const rep = document.getElementById('rep');
const show = () => {
box.style.backgroundPosition = pos.value;
box.style.backgroundRepeat = rep.value;
};
pos.addEventListener('input', show);
rep.addEventListener('input', show);
show();
</script>
</body>
</html>
位置は top right、bottom 10px right 20px、25% 75%、繰り返しは repeat-x、repeat-y、space (切れないように間隔を空けて並べる)、round (ちょうど整数個が収まるようにサイズを調整する) を試してみてください。
重ねる: 複数の背景と文字のオーバーレイ
background-image にはカンマ区切りのリストを指定できます。最初のレイヤーが一番上に描かれます。よくある使い方は、写真の上に半透明のグラデーションを重ねて、白い文字を読みやすくすることです:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Overlay</title>
<style>
body { font-family: system-ui, sans-serif; margin: 0; }
.hero {
--landscape: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200' viewBox='0 0 400 200'%3E%3Crect width='400' height='200' fill='%23bfdbfe'/%3E%3Ccircle cx='320' cy='50' r='24' fill='%23f59e0b'/%3E%3Cpath d='M0 200L120 70L220 200Z' fill='%2316a34a'/%3E%3Cpath d='M140 200L270 90L400 200Z' fill='%2315803d'/%3E%3C/svg%3E");
background-image:
linear-gradient(rgb(17 24 39 / 10%), rgb(17 24 39 / 75%)),
var(--landscape);
background-size: cover;
background-position: center;
aspect-ratio: 16 / 7;
display: flex; align-items: end;
padding: 20px; box-sizing: border-box;
color: white;
}
h1 { margin: 0; font-size: 32px; }
</style>
</head>
<body>
<div class="hero" id="hero"><h1>Readable over an image</h1></div>
</body>
</html>
aspect-ratio が空のボックスに高さを与え、background-size: cover は両方のレイヤーに適用されます。グラデーションの例は CSS グラデーション にまとめています。
background のショートハンド
background は背景のプロパティすべてを 1 行で指定します。サイズは位置のすぐ後にスラッシュで区切って書き、色は最後のレイヤーに書きます:
.hero {
background: url("hero.jpg") center / cover no-repeat, #1f2937;
}
/* the same as */
.hero {
background-image: url("hero.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
background-color: #1f2937;
}
代わりの色は、画像の読み込み中と読み込みに失敗したときに表示されます。ショートハンドで省略したプロパティは初期値にリセットされるので、ショートハンドを先に書き、個別のプロパティはその後に書きましょう。
そのほかの背景プロパティ
| プロパティ | 役割 |
|---|
background-attachment: fixed | ページをスクロールしても画像が動かない (iOS Safari では無視されます) |
background-origin | 位置の基準を border、padding、内容のどの端にするか |
background-clip | 背景を描く範囲。文字の中を塗る text もあります |
background-blend-mode | multiply のようにレイヤー同士を合成する |
よくある間違い
- パスの間違い。 スタイルシートの中の
url() は、HTML ページではなく CSS ファイルからの相対パスです。
- 空の要素。 高さがないので、画像を表示する場所がありません。
no-repeat の付け忘れ。 contain や小さな画像では、画像が繰り返されます。
cover のつもりで 100% 100% を使い、画像を引き伸ばす。
- 重要な画像を背景にする。 内容としての画像には代替テキスト付きの
<img> を使います。背景はスクリーンリーダーから見えません。
- 空白や引用符を含む
data: URL を引用符で囲まない。 常に url("...") と書きましょう。