CSSでテキスト部分だけ背景画像を表示させる方法

完成形はこのようになります

SAMPLE

HTMLの記述はこちら

<div id="sampleBox_210211">
<p id="sampleTxt_210211">SAMPLE</p>
</div>

CSSの記述はこちら

▼ パソコン

#sampleBox_210211 {
max-width: 800px;
width: 100%;
margin: 0 auto;
}

#sampleBox_210211 #sampleTxt_210211 {
/*テキストを切り抜いた時の背景画像を設定します*/
background-image: url(../images/common/sample_bg01.JPG);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
/*背景画像を表示させたいので「透明」にします*/
color: transparent;
text-align: center;
/*「background-clip: text;」で切り抜きます*/
background-clip: text;
-webkit-background-clip: text;
font-size: 78px;
}

▼ スマホ

#sampleBox_210211 {
max-width: 300px;
width: 100%;
margin: 0 auto;
}

#sampleBox_210211 #sampleTxt_210211 {
/*テキストを切り抜いた時の背景画像を設定します*/
background-image: url(../images/common/sample_bg01.JPG);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
/*背景画像を表示させたいので「透明」にします*/
color: transparent;
text-align: center;
/*「background-clip: text;」で切り抜きます*/
background-clip: text;
-webkit-background-clip: text;
font-size: 64px;
}

解説はこちら

SAMPLE

切り抜いた時の背景画像を表示させたいので、テキストの色は「透明」にしたり「rgba」などで文字を透過させましょう。

※現状、「background-clip: text;」は対応ブラウザがChorme、Safariのみとなています。なので「-webkit-background-clip: text;」と指定しておくのがおすすめです

RETURN
top