【CSS】background-size - 背景画像のサイズ

【CSS】background-size - 背景画像のサイズ

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

background-size

background-sizeは背景画像のサイズを示すプロパティです。

基本構文

background-size: 値;

値は数値またはキーワードで定義できます。
一般的な値は次の通りです。

意味
auto 画像比率を維持して画像を拡大縮小します。
contain 表示領域に画像全体を表示するようにサイズを調整します。
cover 表示領域全体に画像を表示するようにサイズを調整します。

サンプル

auto

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

<div></div>

contain

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

<div></div>

cover

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

<div></div>

数値

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

<div></div>