如何创建平滑的渐变背景动画?

时间:2018-10-19 13:44:20

标签: html css3 animation

我创建了一个具有渐变背景的div,并且我想更改此渐变。我应用了一个关键帧动画,该动画立即改变了背景色。如何使此更改顺利进行?

div {
    width: 100px;
    height: 100px;
    background:linear-gradient(red, yellow);
    animation-name: colorchange;
    animation-duration: 5s;
    -webkit-animation-name: colorchange;
   animation-iteration-count: 5;
    -webkit-animation-duration: 5s;
    text-align: center;
}
@keyframes colorchange {
    0% {background:linear-gradient(red, yellow) }
    35% {background:linear-gradient(yellow, green) }
    70% {background:linear-gradient(green, red) }
    100%{background:linear-gradient(red, yellow)}
}
<div>
Gradient Background
</div>

3 个答案:

答案 0 :(得分:1)

尝试一下

    div {
        text-align: center;
        width: 100px;
    	height: 90px;
    	color: #fff;
    	background: linear-gradient(0deg, red, yellow, green);
    	background-size: 400% 400%;
    	-webkit-animation: Gradient 15s ease infinite;
    	-moz-animation: Gradient 15s ease infinite;
    	animation: Gradient 15s ease infinite;

        }
       @-webkit-keyframes Gradient {
    	0% {
    		background-position: 50% 0%
    	}
    	50% {
    		background-position: 50% 100%
    	}
    	100% {
    		background-position: 50% 0%
    	}
    }

    @-moz-keyframes Gradient {
    	0% {
    		background-position: 50% 0%
    	}
    	50% {
    		background-position: 50% 100%
    	}
    	100% {
    		background-position: 50% 0%
    	}
    }

    @keyframes Gradient {
    	0% {
    		background-position: 50% 0%
    	}
    	50% {
    		background-position: 50% 100%
    	}
    	100% {
    		background-position: 50% 0%
    	}
    }
<div> Text </div>

答案 1 :(得分:0)

我可能是错的,但是渐变不支持过渡。

我在其他相关问题中找到了一种解决方法: https://medium.com/@dave_lunny/animating-css-gradients-using-only-css-d2fd7671e759

答案 2 :(得分:0)

就我而言,平滑过渡不适用于渐变背景,而只能用于纯色。

尽管可以创建具有许多颜色的大型渐变背景,然后使用过渡进行移动。这会产生颜色变化的错觉。

body {
	width: 100wh;
	height: 90vh;
	color: #fff;
	background: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
	background-size: 400% 400%;
	-webkit-animation: Gradient 15s ease infinite;
	-moz-animation: Gradient 15s ease infinite;
	animation: Gradient 15s ease infinite;
}

@-webkit-keyframes Gradient {
	0% {
		background-position: 0% 50%
	}
	50% {
		background-position: 100% 50%
	}
	100% {
		background-position: 0% 50%
	}
}

@-moz-keyframes Gradient {
	0% {
		background-position: 0% 50%
	}
	50% {
		background-position: 100% 50%
	}
	100% {
		background-position: 0% 50%
	}
}

@keyframes Gradient {
	0% {
		background-position: 0% 50%
	}
	50% {
		background-position: 100% 50%
	}
	100% {
		background-position: 0% 50%
	}
}

h1,
h6 {
	font-family: 'Open Sans';
	font-weight: 300;
	text-align: center;
	position: absolute;
	top: 45%;
	right: 0;
	left: 0;
}
<h1>Hello World!</h1>