CSS ・ 色・背景
background-position
背景画像の表示位置
背景画像を要素のどこに表示するかを指定します。top・center などの位置を示すキーワードのほか、px や % でも指定できます。
01
サンプルコード
HTML
1<div class="wrap">
2 <div class="box lt">left top</div>
3 <div class="box cc">center center</div>
4 <div class="box lb">left bottom</div>
5</div>
CSS
1.wrap {
2 display: flex;
3 gap: 8px;
4}
5.box {
6 flex: 1;
7 height: 110px;
8 padding: 4px 6px;
9 font-size: 12px;
10 text-align: right;
11 border: 1px solid #ccc;
12 background-color: #f3f2f2;
13 background-image: linear-gradient(#3a9ad9, #3a9ad9);
14 background-size: 32px 32px;
15 background-repeat: no-repeat;
16}
17.lt {
18 background-position: left top;
19}
20.cc {
21 background-position: center center;
22}
23.lb {
24 background-position: left bottom;
25}
02
実行結果
ブラウザでの表示青い四角が背景画像です(例では linear-gradient で画像の代わりにしています)
03
解説
background-position は、背景画像の位置を「横 縦」の順に指定するプロパティです。left top なら左上、center center なら中央、left bottom なら左下に表示されます。
位置は「位置を示すキーワード」「px 指定」「% 指定」などで指定できます。キーワードは top・left・bottom・right・center の5つで、値を1つだけ書くと、もう一方は center になります。
px で指定すると、要素の左上からの距離になります。20px 40px なら左から20px、上から40pxの位置です。right 20px bottom 10px のように書くと、右端・下端からの距離で指定できます。
% は、画像の同じ割合の点を要素の同じ割合の点に合わせます。50% 50% は中央、100% 100% は右下にぴったり寄せた位置です。
04
応用例・注意点
指定できる値
| 値 | 説明 |
|---|---|
top / left / bottom / right / center | 位置を示すキーワード |
left top | 左上(初期値と同じ) |
center center / center | 中央 |
20px 40px | 左から20px、上から40px |
right 20px bottom 10px | 右端から20px、下端から10px |
50% 50% | % で指定(50% 50% は中央) |
写真を中央基準で要素いっぱいに表示する
cover で拡大したとき、どこを基準に切り取るかを center で指定します。
CSS
1.hero {
2 background-image: url("../images/hero.jpg");
3 background-size: cover;
4 background-position: center;
5 background-repeat: no-repeat;
6}
右下に飾りの画像を置く
端からの距離を指定すると、余白を空けて配置できます。
CSS
1.section {
2 background-image: url("../images/leaf.png");
3 background-position: right 16px bottom 16px;
4 background-repeat: no-repeat;
5}
注意点
- 01背景画像を繰り返していると位置の違いが分かりにくいため、background-repeat: no-repeat と組み合わせて使うのが一般的です。
- 02background-image を指定していないと、background-position だけ書いても何も変わりません。