【问题标题】:CSS for creating animated gradient button background用于创建动画渐变按钮背景的 CSS
【发布时间】:2018-07-02 04:57:52
【问题描述】:

我正在寻找可以为button's colored gradient background 创建CSS 动画的CSS 规则。

我只是想玩它,然后这样做了:https://codepen.io/prashant-nadsoftdev/pen/bKzOrB

.custom-btn {
  background: linear-gradient(105deg, #f6d365, #fda085, #f6d365, #ff2400, #e81d1d, #e8b71d, #e3e81d, #1de840, #1ddde8, #2b1de8, #dd00f3, #dd00f3);
  background-size: 200% 200%;
  -webkit-animation: rainbow 5s ease infinite;
  -z-animation: rainbow 5s ease infinite;
  -o-animation: rainbow 5s ease infinite;
  animation: rainbow 5s ease infinite alternate;
  border: 0;
  padding: 25px;
  font-size: 40px;
  color: #fff;
}
@-webkit-keyframes rainbow {
  0%{background-position:0% 100%}
  100%{background-position:100% 0%}
}
@-moz-keyframes rainbow {
  0%{background-position:0% 100%}
  100%{background-position:100% 0%}
}
@-o-keyframes rainbow {
  0%{background-position:0% 100%}
  100%{background-position:100% 0%}
}
@keyframes rainbow { 
  0%{background-position:0% 100%}
  100%{background-position:100% 0%}
}
<body style="text-align:center;">
  <button class="custom-btn">My Button</button>
</body>

我需要颜色一个接一个地在一个方向上(从左到右)。我的代码很接近,但我仍然需要两件事:

  1. 方向错误(颜色变化需要完全相反的方向)。
  2. 它不应该停止。在最后一种颜色之后,它应该采用第一种颜色,然后继续。

【问题讨论】:

标签: css button css-animations linear-gradients keyframe


【解决方案1】:

要让渐变动画在一个方向上无限重复,您需要做的主要事情是调整渐变中的色标:

  1. 重复梯度停止两次。 (这使渐变的结尾看起来像开始,允许动画的每次重复之间平滑过渡。)
  2. 最后再次重复第一个渐变停止。 (这使得最后一站与第一站融为一体。)

您还需要调整关键帧以使它们朝着您想要的方向前进(参见下面的代码)。

.custom-btn {
  background: linear-gradient(105deg,
    /* Base gradient stops */
    #f6d365, #fda085, #f6d365, #ff2400, #e81d1d, #e8b71d, #e3e81d, #1de840, #1ddde8, #2b1de8, #dd00f3, #dd00f3,
    /* Repeat your base gradient stops */
    #f6d365, #fda085, #f6d365, #ff2400, #e81d1d, #e8b71d, #e3e81d, #1de840, #1ddde8, #2b1de8, #dd00f3, #dd00f3,
    /* Repeat your first gradient stop */
    #f6d365);
  
  background-size: 200% 200%;
  animation: rainbow 5s linear infinite;
  border: 0;
  padding: 25px;
  font-size: 40px;
  color: #fff;
}

@keyframes rainbow {
    0% { background-position: 100% 100% }
  100% { background-position: 0% 0% }
}
<body style="text-align:center;">
  <button class="custom-btn">My Button</button>
</body>

【讨论】:

  • 完美!这就是我要找的。​​span>
  • 我想增加它的背景大小是什么。目前是 200%,当我将其增加到 600% 时,它看起来像是在循环后中断。 codepen.io/prashant-nadsoftdev/pen/WymWrQ
  • 而且对于 1200% 的背景大小,基本上我注意到如果我们超过 200%,那么它就会打破循环。
  • 这个答案的一个怪癖是它只保留当前可见颜色“屏幕外”的精确重复,因此按钮的左侧和右侧必须始终淡出同一位。我解决了 3 种颜色(两种 + 一种中间色),并进行了以下更改。background-size: 340% 340%;{background-position: 70% 70% }。我们的想法是我们使背景更大,以便我们的一些颜色在开始时不在按钮上,并且我们在我们一直通过我们的背景之前重新启动动画,所以当颜色与如何对齐时重新启动发生它看着开始。
猜你喜欢
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多