LoginSignup
1
1

More than 1 year has passed since last update.

background-clipを使って文字にアクセントをつける

Last updated at Posted at 2022-09-19

はじめに

CSSで文字にグラデーションをつけたいけどcolorではできない!ということから始まり色々調べたら応用が利きそうなのでまとめてみました。

background-clipとは?

要素の背景をどこまでにするか?ということを設定できるようです。

プロパティの種類

border-box : 要素の境界の外の辺まで

要素の外側(borderの部分)まで広げます。borderとの境は下に入るようです。

p{
  width:300px;
  text-align:center;
  font-size:40px;
  font-weight:bold;
  padding:1em;
  background-color:red;
  border:5px dashed #000;
  background-clip:border-box;
}

image.png

padding-box : 要素のpaddingの外側まで

一見border-boxとの違いは無いように見えますが、borderの部分はbackgroundには入りません。
border-boxとpadding-boxは"borderに重なるかどうか"が大きな違いのようです。

p{
  width:300px;
  text-align:center;
  font-size:40px;
  font-weight:bold;
  padding:1em;
  background-color:red;
  border:5px dashed #000;
  background-clip:padding-box;
}

スクリーンショット 2022-09-19 173739.png

content-box : 要素の外側まで

要素の幅と高さがそのまま背景になります。
ここではwidthを300pxしているので幅は300px、高さはfont-sizeの40pxにline-height(指定していないのでnormalの1.2)の値を掛けて60pxとなっています。

p{
  width:300px;
  text-align:center;
  font-size:40px;
  font-weight:bold;
  padding:1em;
  background-color:red;
  border:5px dashed #000;
  background-clip:content-box;
}

スクリーンショット 2022-09-19 173848.png

text : テキスト部分のみ

テキスト部分のみを切り取って背景とします。
ここではちょうど、color:red; を指定した時と同じようになります。
textはchromeやoperaなどのブラウザは完全対応ではないので、-webkit-background-clip: text;と記述する必要があるそうです。
そのままではデフォルトのcolorが適用されてしまうので、color:rgba(0,0,0,0);や-webkit-text-fill-color: transparent; を併せて記述することでbackground-colorが適用されます。

p{
  width:300px;
  text-align:center;
  font-size:40px;
  font-weight:bold;
  padding:1em;
  background-color:red;
  border:5px dashed #000;
  -webkit-background-clip: text;
  color:rgba(0,0,0,0);
}

スクリーンショット 2022-09-19 173549.png

どんなことに応用できるか?

1.文字にグラデーションをつける

colorでは文字にグラデーションを付けることはできませんでしたが、background:linear-gradientを使えば、文字にグラデーションをつけることができました。

p{
    text-align:center;
    font-size:100px;
    font-weight:bold;
    padding:1em;
    background: linear-gradient(to right, blue 0% ,red 100%);
    border:5px dashed #000;
    -webkit-background-clip: text;
    color:rgba(0,0,0,0);
  }

スクリーンショット 2022-09-19 174353.png

2.文字に背景画像をつける

background-imageで画像を指定すれば、文字の背景に画像を指定することが出来ました。
gif画像を設定すれば、アニメーションのように実装することも出来るそうです。

  p{
    text-align:center;
    font-size:100px;
    font-weight:bold;
    padding:1em;
    background-image:url('main2.jpg');
    background-position: center;
    border:5px dashed #000;
    -webkit-background-clip: text;
    color:rgba(0,0,0,0);
  }

image.png

参考

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1