Floy Rodd Floy Rodd - 5 months ago 72
CSS Question

CSS - smooth button gradient color transition on hover

I have the following button.

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.

Answer

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.

NOTE: Not all browsers support transitions on pseudo elements, so you may need to add empty elements to achieve the same effect on older/unsupported browsers.

.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>