mattvent
mattvent

Reputation: 381

CSS Change background color with transition

my page has three background colors that change depending on what a div displays (just a word actually).

The colors do change right now, but the transition is not smooth as expected. Colors just change brutally, without a transition operating.

Here is my CSS :

.gradient-low{
background: #ddd6f3;
background: -webkit-linear-gradient(to left, #faaca8 , #ddd6f3);
background: linear-gradient(to left, #faaca8 , #ddd6f3);
transition-duration: 0.4s;
}

.gradient-moderate{
background: #ff6e7f;
background: -webkit-linear-gradient(to left, #ff6e7f , #bfe9ff);
background: linear-gradient(to left, #ff6e7f , #bfe9ff);
transition-duration: 0.4s;
}

.gradient-high{

background: #EECDA3;
background: -webkit-linear-gradient(to left, #EF629F , #EECDA3);
background: linear-gradient(to left, #EF629F , #EECDA3);
transition-duration: 0.4s;
}

Do you have any suggestions so the change of colour is operated gradually and smoothly ?

Upvotes: 1

Views: 6307

Answers (2)

Mike Stringfellow
Mike Stringfellow

Reputation: 497

Unfortunately you can't transition CSS gradients at present. You can, however, work around this to achieve a similar effect.

The CSS below moves the gradients to ::before pseudo-classes. Because these gradients are now from transparent to the secondary colour, the solid colour background transition on the classes themselves is visible in the background.

.gradient-low {
    background: #ddd6f3;
    transition: background 0.4s;
}

.gradient-low::before {
    height: 100%;
    width: 100%;
    content: '';
    position: absolute;
    left: 0px;
    top: 0px;
    background: linear-gradient(to left, #faaca8 , rgba(0,0,0,0));
}

Full fiddle here: https://jsfiddle.net/mstringfellow/zftzrobv/

Upvotes: 1

Nayana_Das
Nayana_Das

Reputation: 1817

Using transition it is not possible, but we can use CSS animation and keyframe animation. Try this :

.gradient-high{

background: #EECDA3;
background: -webkit-linear-gradient(to left, #EF629F , #EECDA3);
background: linear-gradient(to left, #EF629F , #EECDA3);
 animation-name: drop;
  animation-iteration-count: 1;
  animation-timing-function: ease-out;
  animation-duration: 5s;
}

@keyframes drop {
  0% {
    transform: translateY(-100%);
  }
  100% {
    transform: translateY(50);
  }
}

Please check out the FIDDLE

Upvotes: 1

Related Questions