テキストにグラデーションを設定する

CSSでテキストにグラデーションを設定する方法をメモ。

対応ブラウザ

テキストのグラデーションには、背景にグラデーションを設定する「background: linear-gradient()」、背景をテキスト内に切り取って表示する「background-clip: text」、テキストの塗りの色を透明にする「text-fill-color: transparent」を使用します。

「background: linear-gradient()」の対応ブラウザは、最新のブラウザであれば概ね対応しています。

「background-clip」の場合、Firefox、ChromeとSafariでは「-webkit-background-clip: text」の形でサポートしているようです。

「text-fill-color」の場合はIEに対応していないため、別途対応が必要になります。
 

設定方法

縦方向と横方向のグラデーションを設定してみます。

<p class="gradation-text-h">縦方向のグラデーション</p>
<p class="gradation-text-w">横方向のグラデーション</p>

横方向の場合は要素の幅分だけグラデーションが広がってしまうので、display:inline-block を使って幅をテキストと同じになるようにします。

.gradation-text-h {
	background: linear-gradient(0deg, red, blue);
	-webkit-background-clip: text;
	background-clip: text;
	-webkit-text-fill-color: transparent;
}
.gradation-text-w {
	display: inline-block;
	background: linear-gradient(90deg, red, blue);
	-webkit-background-clip: text;
	background-clip: text;
	-webkit-text-fill-color: transparent;
}

これでテキストにグラデーションを設定することができました。
テキストにグラデーションを設定するデモページ
 

IEの対応

IEでは対応していないため、グラデーションではなくベタ塗りの文字を表示するようにしてみます。

.gradation-text-h {
	background: linear-gradient(0deg, red, blue);
	-webkit-background-clip: text;
	background-clip: text;
	-webkit-text-fill-color: transparent;
}
@media all and (-ms-high-contrast: none) { /* IE10,11用 */
	.gradation-text-h {
		background: none;
		color: red;
	}
}
.gradation-text-w {
	display: inline-block;
	background: linear-gradient(90deg, red, blue);
	-webkit-background-clip: text;
	background-clip: text;
	-webkit-text-fill-color: transparent;
}
@media all and (-ms-high-contrast: none) { /* IE10,11用 */
	.gradation-text-w {
		background: none;
		color: red;
	}
}

@media all and (-ms-high-contrast: none) { ~ }でIE10以上にCSSを適用させています。
IEでべた塗りにするデモページ
 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年3月
 12
3456789
10111213141516
17181920212223
24252627282930
31