CSS: カンマ区切りで背景画像を複数指定する
CSS2.1 までは背景に指定できる画像は1つのみでしたが、 CSS3 からは複数の画像を指定できるようになりました。
複数指定するには background プロパティを使ってまとめて指定する方法と、 個別のプロパティを使って指定する方法があります。 どちらも複数の値をカンマ区切りで指定します。
複数背景画像を指定する使用例
/* background プロパティで一括指定する場合 */
background: url("sample1.png") no-repeat 100px 50px,
url("sample2.png") no-repeat 20px 10px;
/* 個別のプロパティで指定する場合 */
background-image: url("sample1.png"), url("sample2.png");
background-repeat: no-repeat, no-repeat;
background-position: 100px 50px, 20px 10px;
上記の2つの指定方法はどちらの方法でも同じ結果となります。 自分のやりやすい方法で記述してください。
背景画像を複数指定するサンプルコード
下のサンプルは、div 要素の中に2つの背景画像を指定しています。 手のマークとニワトリの画像です。 background-position プロパティで2つの画像が重ならないように位置を調整しています。
<div class="sample1"></div>
<style>
div.sample1 {
width: 250px;
height: 250px;
border: 1px solid black;
background-image: url("../img/hand.png"), url("../img/tori.png");
background-repeat: no-repeat, no-repeat;
background-position: 10px 10px, 10px 0px;
}
</style>