背景画像を自在に配置する
特定のHTML要素の背景に画像を配置する際は、background-positionプロパティで表示位置を指定します。
調整前のCSS コード例
section {
background-image: url(./images/star.svg);
background-position: right 10% bottom 10%;
background-repeat: no-repeat;
background-size: 40% auto;
}
HTML コード例
<section>
<h2>背景画像の位置を指定する</h2>
<p>背景に画像を配置する場合、background-positionプロパティを使います。</p>
</section>

背景画像の位置の指定方法について、いくつかのパターンを交えながら解説していきます。
左右、上下、中央のみ指定する
あらかじめ用意された「left」や「center」などの値を使って、x軸とy軸の位置をそれぞれ指定する最もシンプルで手軽な方法です。
指定できる値には次の6種類があります。
向き | 値 |
---|---|
X軸 | left、center、right |
Y軸 | top、center、bottom |
値のイメージはこのようになります。
「center」は共通で使用できる値です。

続いて、具体的な指定例を確認していきましょう。
値を1つだけ指定する
値は1つ指定した場合はX軸、Y軸のいずれか(指定されなかった方は 「center」)となります。
CSS コード例
/* background-positioプロパティに「left」を指定 */
section {
background-image: url(./images/star.svg);
background-position: left;
background-repeat: no-repeat;
background-size: 40% auto;
}

CSS コード例
/* background-positioプロパティに「bottom」を指定 */
section {
background-image: url(./images/star.svg);
background-position: bottom;
background-repeat: no-repeat;
background-size: 40% auto;
}

CSS コード例
/* background-positioプロパティに「bottom」を指定 */
section {
background-image: url(./images/star.svg);
background-position: center;
background-repeat: no-repeat;
background-size: 40% auto;
}

値を2つ指定する
値を2つ指定していきます。
X軸、Y軸のどちらから指定しても大丈夫です。
CSS コード例
/* background-positioプロパティに「right bottom」を指定 */
section {
background-image: url(./images/star.svg);
background-position: right bottom;
background-repeat: no-repeat;
background-size: 40% auto;
}

CSS コード例
/* background-positioプロパティに「left top」を指定 */
section {
background-image: url(./images/star.svg);
background-position: left top;
background-repeat: no-repeat;
background-size: 40% auto;
}

数値を使って位置を詳細に指定する
背景画像の位置は上記の「left」などの値に加えて、具体的に数値で指定することもできます。
CSS コード例
/* 右から35%、下から5%の位置を指定 */
section {
background-image: url(./images/star.svg);
background-position: right 35% bottom 5%;
background-repeat: no-repeat;
background-size: 40% auto;
}

X軸かY軸のどちらか1つだけ指定する形でも問題ありません。
CSS コード例
/* X軸は「right」、Y軸のみ数値で下から20pxを指定 */
section {
background-image: url(./images/star.svg);
background-position: right bottom 20px;
background-repeat: no-repeat;
background-size: 40% auto;
}

数値のみで指定することも可能です。
その場合は1つ目はX軸の指定、2つ目はY軸の指定となります。
また、それぞれで「px」や「%」のように異なる単位を指定できます。
CSS コード例
/* X軸は「right」、Y軸のみ数値で下から20pxを指定 */
section {
background-image: url(./images/star.svg);
background-position: 50% 150px;
background-repeat: no-repeat;
background-size: 40% auto;
}
