CSS-悬停时平滑的按钮渐变颜色过渡 [英] CSS - smooth button gradient color transition on hover

查看:55
本文介绍了CSS-悬停时平滑的按钮渐变颜色过渡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下按钮.

上方按钮的CSS是这样的:

The CSS for the button above is this:

.cta-btn {
  display: inline-block;
  margin: 20px 0 0 20px;
  color: #fff;
  background-color: #FF8F1B;
  background-image: linear-gradient(to right, #2ab3ff, #ff2d00);
  box-shadow: 4px 5px 27px 4px rgba(220, 120, 184, 0.85);
  font-size: 21px;
  border-radius: 30px;
  padding: 12px 21px;
  font-family: Montserrat;
}

<a href="#" class="cta-btn">click me</a>

当鼠标悬停在按钮上时,我希望按钮可以平滑地更改渐变颜色.我不希望将渐变颜色悬停在按钮上.这是我尝试进行平滑渐变颜色过渡的尝试:

I want the button to change gradient color smoothly when I hover over it. I do not want the gradient color to just snap onto the button when I hover it. This is my attempt at a smooth gradient color transition:

a.cta-btn:hover {
  background-image: linear-gradient(to right,#FF2A67,#FF5D3A);
  color: #fff;
  box-shadow: 4px 5px 27px 4px rgba(255,45,45,0.85);
  transition: background-image .3s linear;
  transition: box-shadow .3s linear;
}

我们非常感谢您的帮助.

Any help is much appreciated.

推荐答案

简短的回答,您不能仅使用背景.但是,您可以使用内部的其他元素(或伪元素)并在悬停时使其淡入来实现类似的效果.

Short answer, you can't using just background. However, you can achieve a similar effect using other elements (or pseudo elements) inside and fading them in on hover.

以下示例将两个伪元素用作两个背景状态.悬停时,我们只需淡入新的背景即可获得类似的过渡效果,如果渐变可以过渡,则会发生这种情况.

The following example uses two pseudo-elements as the two background states. On hover, we simply fade-in the new background giving a similar transition effect that would happen if gradients were transition-able.

注意:并非所有浏览器都支持对伪元素的转换,因此您可能需要添加空元素,以在较旧/不受支持的浏览器上实现相同的效果.

.cta-btn {
  position: relative;
  display: inline-block;
  margin: 20px 0 0 20px;
  color: #fff;
  box-shadow: 4px 5px 27px 4px rgba(220, 120, 184, 0.85);
  font-size: 21px;
  border-radius: 30px;
  overflow: hidden;
  padding: 12px 21px;
  font-family: Montserrat;
  transition: box-shadow.3s ease-in-out;
  text-decoration: none;
}

/* These are the two backgrounds, absolutely positioned to cover. */
.cta-btn::before,
.cta-btn::after {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background-image: linear-gradient(to right, #2ab3ff, #ff2d00);
  border-radius: 30px;
  z-index: -1;
}

.cta-btn::after {
  opacity: 0;
  background-image: linear-gradient(to right,#FF2A67,#FF5D3A);
  transition: opacity.3s ease-in-out;
}

/* On hover, transtiion the shadow of the anchor, and fade in the after element to show the new background. */
.cta-btn:hover {
  box-shadow: 4px 5px 27px 4px rgba(255,45,45,0.85);
}
.cta-btn:hover::after {
  opacity: 1;
}

<a href="#" class="cta-btn">click me</a>

这篇关于CSS-悬停时平滑的按钮渐变颜色过渡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆