Анимированный градиент на чистом CSS
Приветствую, друзья, сегодня создадим анимированный градиент на чистом CSS, без использования библиотек, плагинов или даже JavaScript’a. Очень многих новичков, да и не только, интересует как сделать анимированный градиентный фон для сайта. Сегодня мы реализуем это в несколько строк кода. В результате вы научитесь делать анимированный градиент для сайта. В будущем вы можете его использовать для создания красивых фонов.
Как всегда, готовый пример анимированного градиента и код вы можете посмотреть на codepen .
Анимированный градиент — код и пояснения
Для начала разберемся с HTML частью. Тут ничего особенного не нужно, только создать элемент, для которого мы будем делать градиент. Я буду делать для элемента с class=»gradient» . Вы можете использовать это даже для тега <body> , если градиент нужен на всем сайте.
Теперь перейдем к css части. Вся суть анимации в том, что мы делаем градиент больше самого блока. У меня это 400% его размера. После чего добавляем анимацию, которая будет двигать градиент по нашему блоку. За счет этого мы и получим анимацию градиента.
Код достаточно простой. Единственная сложность, которая может у вас возникнуть, это создание самого градиента и подбор цветов. Что бы упростить этот этап — вы можете использовать один из генераторов css градиента .
Результат
Спасибо, что прочитали! Если у вас остались любые вопросы — задавайте их в комментариях на Youtube, или напишите мне в Telegram. С радостью помогу и отвечу на ваши вопросы.
Так же буду очень благодарен, если вы ознакомитесь с другими моими уроками:
How to Animate Gradients using CSS
I want to move my gradient that has multiple colors smoothly but the problem is that the animation is not smooth. It just changes its position at every step.
Is it possible to accomplish without using jQuery?
![]()
5 Answers 5
Please try this code:
Dynamic implementation of Dave’s answer:
![]()
![]()
Using CSS variables it’s now a trivial task.
Here is a basic example (hover to see the result)
![]()
Here is another way. The following has the static gradient containing all phases of the animation, which is then moved inside the outer element. This allows to perform animation smoothly (as the topic suggests), because the only animation here is the element position.
Please note that for the sake of performance the gradient element left unchanged. Although the question was to animate the gradient, moving the background does practically the same thing, while the performance wins!
Set the body margin and padding to 0. Set an html rule to 100% height (higher than 100% may be required).
Set the body to the end state for the gradient.
Create an empty div with a background which is the start state for the gradient. Give the empty div 100% height.
Give both the body and the empty div a background-attachment: fixed;
Create a wrapper for your body content.
Set the empty div to position: fixed; Set the wrapper to position: relative; Give both a z-index, the wrapper being higher.
Create an animation that will change the opacity of the empty div from 1 to 0 over the desired time. Add animation-fill-mode:forwards; to the div rule so the animation stays where it ends.
It’s not as sexy as a real animated gradient shift, but it’s as simple as you can get with CSS only and keyframes, I think.
Creating gradient animation with CSS
In this post, I will go through on how to create gradient animations for your web design. Having the background gradient animations can make the design modern and grab the user’s attention at a specific area of the page.
Please enable JavaScript
For example, you can have a gradient background that animates on the hero or marketing section of the page.
We can also incorporate this into buttons or cards when people hover over.
How do we create background gradients?
Before figuring out how to animate the background, we first need to figure out how to create a background gradient. The simplest way to create a background gradient is with the CSS property:
linear-gradient is a CSS function that creates a image that transitions between two or more colours along a linear line (more info here: https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient)
So for the above code, we have a background that has a linear gradient of start colour #e66465 and end colour of #9198e5
The linear-gradient function can be even more complex examples. For example you can specify the angle of 45 degrees and go from blue to red:
Another complex example is to specify the colour going from bottom to top, start with blue colour, turn green at 40% of the transition and finally finish transition into red:
Background gradient animation with pure CSS
So now that we know how gradients work, we can add @keyframe animations to animate the gradient
The HTML that we need to create this effect is just making sure that we have body :
As with the CSS, it will look like the following. I will go through it line by line:
The body stying, we use background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); . This means that we want the background to have a linear gradient of negative 45 degrees. The background will have 4 colours — starting with #ee7752 , #e73c7e , #23a6d5 , and finally finishing with #23d5ab .
We also want the background to be huge: background-size: 400% 400%; . The basic idea is that we have a huge background with 4 colours. So when viewing the background, you can only see one or two colours at a time. When we animate, we will move the background along the x axis (horizontal). This will give the impression that the gradient is animating.
To create the animation, we define the @keyframes gradient . This just animates the background along horizontally and repeats infinitely.
When the animation starts, we set background-position: 0% 50%; .
At the 50% @keyframe we move the background position 100% in the x axis (horizontal) and back to 0% at the end of the animation.
Note: that we need to move 100% along the x position when we are at the 50% — this is because we are making our animation to be infinite. Moving along to 100% of the x axis at the end of the animation will make it look janky.
Browser support
Since this technique relies on the linear-gradient function — it is mostly supported across modern browsers — even IE 10 and 11. Lower versions of IE will need to use the property:
Additionally keep in mind the angle parameter! Based on the MDN spec, value of 0deg is equivalent to to top; when we increase the values rotate clockwise from there.
linear-gradient(0deg, blue, green 40%, red);
However with some browser versions such as Safari or Opera angle is treated differently. For example on Safari 5-6, and Opera browsers, the angle starts to the right, instead of the top. For example, it considered an angle of 0deg as a direction indicator pointing to the right.
Some tips
- Keep in mind animation principles with this since having too much of this in your design can ruin it. Make sure this effect supports your content — eg not animate for its own sake.
- Make sure to use appropriate colours and contrasts. Keep to save web accessible colours to not disorient and confuse the user. For our example above, I would prefer to have white text for the purple/ blue background to keep high contrast.
- Keep performance in mind when using this technique. Having @keyframes will add to your site’s performance cost and can reduce it further if you have a lot objects animating at the same time.
Final thoughts
Animating backgrounds with CSS can be a great way to grab a user’s attention or bring a design to be more modern.
We can acheive this by using a combination of linear-gradient CSS function and @keyframes . The basic idea is that we have a huge background with 4 colours that transition to create the gradient background. We will then animate this infinitely by moving the background horizontally — back and forth.
When coding this, make sure to keep in mind to use it sparingly, understand the colours, contrast and performance issues that could pop up.
Additionally since this technique relies on CSS gradient functions, we need to consider and cater for different browsers such as internet explorer, Safari, and Opera.
About the Author
G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.
My aim to share what I have learnt with you! (and to help me remember )
CSS Gradients
CSS gradients let you display smooth transitions between two or more specified colors.
CSS defines three types of gradients:
- Linear Gradients (goes down/up/left/right/diagonally)
- Radial Gradients (defined by their center)
- Conic Gradients (rotated around a center point)
CSS Linear Gradients
To create a linear gradient you must define at least two color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along with the gradient effect.
Syntax
Direction — Top to Bottom (this is default)
The following example shows a linear gradient that starts at the top. It starts red, transitioning to yellow:
Example
Direction — Left to Right
The following example shows a linear gradient that starts from the left. It starts red, transitioning to yellow:
Example
Direction — Diagonal
You can make a gradient diagonally by specifying both the horizontal and vertical starting positions.
The following example shows a linear gradient that starts at top left (and goes to bottom right). It starts red, transitioning to yellow:
Example
Using Angles
If you want more control over the direction of the gradient, you can define an angle, instead of the predefined directions (to bottom, to top, to right, to left, to bottom right, etc.). A value of 0deg is equivalent to "to top". A value of 90deg is equivalent to "to right". A value of 180deg is equivalent to "to bottom".
Syntax
The following example shows how to use angles on linear gradients:
Example
Using Multiple Color Stops
The following example shows a linear gradient (from top to bottom) with multiple color stops:
Example
The following example shows how to create a linear gradient (from left to right) with the color of the rainbow and some text:
Example
Using Transparency
CSS gradients also support transparency, which can be used to create fading effects.
To add transparency, we use the rgba() function to define the color stops. The last parameter in the rgba() function can be a value from 0 to 1, and it defines the transparency of the color: 0 indicates full transparency, 1 indicates full color (no transparency).
The following example shows a linear gradient that starts from the left. It starts fully transparent, transitioning to full color red:
Example
Repeating a linear-gradient
The repeating-linear-gradient() function is used to repeat linear gradients: