【CSS】background-position - 背景画像の位置

【CSS】background-position - 背景画像の位置

CSSのbackground-positionプロパティについてご紹介します。

background-position

background-positionは背景画像の位置を示すプロパティです。
位置はbackground-originからの相対位置です。

基本構文

background-position: X座標, Y座標;

特定の位置はキーワードで用意されています。
一般的なキーワードは次の通りです。

意味
top X軸:表示範囲に対して画像が中央の位置
Y軸:表示範囲の上端と画像の上端を揃える位置
bottom X軸:表示範囲に対して画像が中央の位置
Y軸:表示範囲の下端と画像の下端を揃える位置
left X軸:表示範囲の左端と画像の左端を揃える位置
Y軸:表示範囲に対して画像が中央の位置
right X軸:表示範囲の右端と画像の右端を揃える位置
Y軸:表示範囲に対して画像が中央の位置
center 表示範囲の中央の位置

サンプル

top

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: top;
}
</style>

<div></div>

bottom

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: bottom;
}
</style>

<div></div>

left

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: left;
}
</style>

<div></div>

right

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: right;
}
</style>

<div></div>

center

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: center;
}
</style>

<div></div>

数値

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: 25% 25%;
}
</style>

<div></div>

オフセット

<style>
div {
    width: 250px;
    height: 250px;
    border: 1px solid black;
    background-image: url('https://it-hack.net/storage/app/media/image/app-programing%40100x66.jpg');
    background-repeat: no-repeat;
    background-position: top 25% right 25%;
}
</style>

<div></div>