CSSのグラデーション(linear-gradient)はtransitionで色変化が出来ない

2023/08/10 (木) - 00:00 CSS

CSSでlinear-gradientプロパティを使いグラデーションボタンを作り、hoverしたらtransitionプロパティでグラデーションの色がフワッと変わる実装をしようとしたけどうまく動かなかった…。デュレーションがかからず即時色が変わってしまう…🥺

グラデーション

検証の結果グラデーション(linear-gradient)をtransitionで変化できないことが判明。

諦めようと思ったけど、せっかくなのでと無理やりtransitionでグラデーションの色が変化したっぽい見た目になるよう実装したので、そのメモ。

方法としては、あらかじめhover時用の色変化グラデーションのスプライトをbefore擬似要素でボタンと同じ大きさで用意して透明にしておき、hoverしたときに擬似要素の透明度を上げてtransitionでフワッと変わるようにした。

グラデーション

HTML

<a href="#" class="btn_sample">ボタンです</a>

CSS

.btn_sample{
 display:inline-block;
 position:relative;
 z-index:1;
 box-shadow: 0 0 15px 1px rgba(0,0,0,0.25);
 overflow: hidden;
 transition: 0.5s;
 padding: 1rem 2rem;
 text-decoration: none;
 border-radius: 2rem;
 background-image: linear-gradient(#cb003a, #ff749c);
 font-size: 1rem;
 font-weight: bold;
 color:#fff;
}
.btn_sample:focus,
.btn_sample:hover{
 box-shadow: 0 0 5px 1px rgba(0,0,0,0.1);
 transform: scale(1.025);
 color:#7f0024;
}

/*変化後のグラデーションを不可視で生成*/
.btn_sample::before{
 content: "";
 display: block;
 position: absolute;
 width: 100%;
 top: 0;
 left: 0;
 bottom: 0;
 transition: 0.5s;
 background-image: linear-gradient(#ffe9ef, #eb7c9c);
 z-index:-1;
 opacity: 0;
}
/*変化後のグラデーションを可視化*/
.btn_sample:focus::before,
.btn_sample:hover::before{
 opacity: 1;
}

HTMLに変更を加えずに実装させるとなるとこれがベターかなと…。transitionの影響を受けない視覚系プロパティもあるので注意しなくては…🥹

おしまい

記事をシェアする

  • facebookでシェアする
  • twitter(X)でシェアする
  • LINEでシェアする
  • はてなブックマークでシェアする
  • Pocketでシェアする
  • Pinterestでシェアする

トラックバック & ピンバック

この記事へのトラックバックURI
https://weblog.walk-life.me/linear-gradient_transition/trackback/

コメント

コメントは下記からどうぞ

ページの先頭へ