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

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

CSSのbackground-sizeプロパティについて解説します。

検証環境

background-size

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

基本構文

background-size: 値;

代表的な値は次の通りです。

説明
auto 画像比率を維持して画像を拡大縮小
contain 表示領域に画像の全体を表示するようにサイズを調整
cover 表示領域の全体に画像を表示するようにサイズを調整
任意の数値 数値のサイズに調整

サンプル

auto

<style>
p {
    color: silver;
    background-image: url('https://it-hack.net/storage/app/media/document/development/programming/css/properties/background-size/hacker-commandline.jpeg');
    background-repeat: no-repeat;
    ___ih_hl_start
    background-size: auto;
    ___ih_hl_end
}
</style>

<p>
    CSS : Cascading Style Sheets.<br>
    CSS is a programming language<br>
    that decorates elements such as HTML and XML.<br>
    You can set various properties<br>
    such as text color, background, and size.
</p>

contain

<style>
p {
    color: silver;
    background-image: url('https://it-hack.net/storage/app/media/document/development/programming/css/properties/background-size/hacker-commandline.jpeg');
    background-repeat: no-repeat;
    ___ih_hl_start
    background-size: contain;
    ___ih_hl_end
}
</style>

<p>
    CSS : Cascading Style Sheets.<br>
    CSS is a programming language<br>
    that decorates elements such as HTML and XML.<br>
    You can set various properties<br>
    such as text color, background, and size.
</p>

cover

<style>
p {
    color: silver;
    background-image: url('https://it-hack.net/storage/app/media/document/development/programming/css/properties/background-size/hacker-commandline.jpeg');
    background-repeat: no-repeat;
    ___ih_hl_start
    background-size: cover;
    ___ih_hl_end
}
</style>

<p>
    CSS : Cascading Style Sheets.<br>
    CSS is a programming language<br>
    that decorates elements such as HTML and XML.<br>
    You can set various properties<br>
    such as text color, background, and size.
</p>

数値

<style>
p {
    color: silver;
    background-image: url('https://it-hack.net/storage/app/media/document/development/programming/css/properties/background-size/hacker-commandline.jpeg');
    background-repeat: no-repeat;
    ___ih_hl_start
    background-size: 70%;
    ___ih_hl_end
}
</style>

<p>
    CSS : Cascading Style Sheets.<br>
    CSS is a programming language<br>
    that decorates elements such as HTML and XML.<br>
    You can set various properties<br>
    such as text color, background, and size.
</p>