CSS - 悬停时平滑按钮渐变颜色过渡

Flo*_*odd 4 css

我有以下按钮。

上面按钮的 CSS 是这样的:

.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;
}
Run Code Online (Sandbox Code Playgroud)
<a href="#" class="cta-btn">click me</a>
Run Code Online (Sandbox Code Playgroud)

当我将鼠标悬停在按钮上时,我希望按钮能够平滑地更改渐变颜色。当我悬停按钮时,我不希望渐变颜色只是捕捉到按钮上。这是我尝试平滑渐变颜色过渡:

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;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢。

rgt*_*ree 6

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

下面的示例使用两个伪元素作为两个背景状态。在悬停时,我们简单地淡入新背景,提供类似的过渡效果,如果渐变是可过渡的,就会发生这种情况。

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

.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;
}
Run Code Online (Sandbox Code Playgroud)
<a href="#" class="cta-btn">click me</a>
Run Code Online (Sandbox Code Playgroud)