15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【CSS】mask-imageプロパティで簡単にSVGの色変えができた

Posted at

hover時、ナビのカレント時など同じアイコンで色だけ変えたいときに、別の色にした別画像で書き出すのが面倒で悩み続けてきました。
useタグを使う方法もありましたが、何故かうまくできず、、、
そこで出会ったmask-imageがかなり優秀だったので備忘録です。

mask-imageの使い方

基本的にbackground-imageと同じように扱えます。
mask-imageにSVGのファイルパスを指定し、mask-positionmask-repeatmask-sizeをそれぞれ指定します。

SCSS
.nav-item {
  display: inline-block;
  width: 32px;
  height: 32px;
  // mask関連の指定
  mask-position: center center;
  mask-repeat: no-repeat;
  mask-size: contain;
  mask-image: url(../img/icon-home.svg);
  background: navy; // 背景色でSVGの色を指定
  &--green {
    background: green; // 背景色でSVGの色を指定
  }
  &:hover {
    background: red; // 背景色でSVGの色を指定
  }
}
HTML
<a class="nav-item"></a>
<a class="nav-item nav-item--green"></a>

image.png

::befoer ::after にももちろん使えるのでかなり便利です!!

15
12
0

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
15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?