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

2023-12-21

我有以下按钮。

上面按钮的 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;
}
<a href="#" class="cta-btn">click me</a>

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

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;
}

任何帮助深表感谢。


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

以下示例使用两个伪元素作为两个背景状态。悬停时,我们只需淡入新背景,即可提供与渐变可转换时类似的转换效果。

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

.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CSS - 悬停时平滑按钮渐变颜色过渡 的相关文章

随机推荐