10
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

擬似要素で設置したSVGの色を変えたい

Posted at

はじめに

擬似要素(before,after)でSVG画像を設置したけどhoverで色も変えたい!
そんなときに使えるちょうどいいCSSがありましたのでご紹介します。

とにかくすぐにコードを確認しながら試したい方はこちら

Codepen
https://codepen.io/takuma348/pen/vYRKZJm
hover.gif

今回キーとなるCSSプロパティ

  • background-color
  • mask-image
  • mask-size:

コード

HTML

<div class="wrapper">
  <button class="button"></button>
</div>

CSS(SCSS)

.wrapper {
  height: 100vh;
  width: 100%;

  display: flex;
  justify-content: center;
  align-items: center;
}

.button {
  background-color: #fff;
  border: 2px solid #000;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  transition: background-color 0.4s;

  height: 60px;
  width: 60px;

  &::before {
    display: block;
    content: "";
    background-color: #000;
    transition: background-color 0.4s;

    -webkit-mask-image: url('data:image/svg+xml;utf-8,<svg xmlns="http://www.w3.org/2000/svg" fill="%2332CD32" viewBox="0 0 16 16"><path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425a.247.247 0 0 1 .02-.022Z"/></svg>');
    -webkit-mask-size: contain;
    mask-image: url('data:image/svg+xml;utf-8,<svg xmlns="http://www.w3.org/2000/svg" fill="%2332CD32" viewBox="0 0 16 16"><path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425a.247.247 0 0 1 .02-.022Z"/></svg>');
    mask-size: contain;

    height: 35px;
    width: 35px;

    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

@media (hover: hover) and (pointer: fine) {
  .button:hover {
    background-color: #000;

    &::before {
      background-color: #fff;
    }
  }
}

スマホ対応もしたい方は:activeontouchstart=""を使って応用してみてください。
最後まで読んでいただきありがとうございました!

10
2
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
10
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?