Circular gradient css. CSS: Radial gradient for background. Radial gradient radial-gradient()
CSS functionsDefinition and Application
The CSS function radial-gradient() is positioned along its radius, extending outward from the center of the element in a circular or elliptical shape, with the colors of the gradient distributed evenly throughout the element's space.
The principle of creating radial gradients is similar to creating linear gradients (linear-gradient()), for this you just need to specify the starting color - it will be located in the middle of the gradient and the ending color, which will be located at the end of the gradient.
You can find out more about working with gradients in the articles “” and “”. Please note that the articles highlight the nuances of working with old browsers and provide numerous examples.
Browser support
Function | Opera | IExplorer | Edge |
|||
---|---|---|---|---|---|---|
radial-gradient() | 26.0 10.0 -webkit- | 16.0 3.6 -moz- | 12.1 11.1 -o- | 6.1 5.1 -webkit- | 10.0 | 12.0 |
CSS syntax:
background-image / background : radial-gradient ([keyword shape (or size)] at position x-axis y-axis , color 1 – stop 1, . . . , color n – stop n);Form
Elliptical shape is defined by the ellipse value, which is the default (no need to specify it), and the circular shape is defined by the circle value.
Keyword
The gradient is calculated based on the distance to near/far side, or nearest / farthest corner element.
Meaning | Description |
---|---|
closest-side | The gradient is calculated based on the distance to the closest side of the element from its center for round gradients ( x axis or y axis) and to the nearest parties ( x axis And y axis) if the gradient is in the shape of an ellipse. background-image: radial-gradient(circle closest-side at 60% 60%, plum, black, orange); background-image: radial-gradient(ellipse closest-side at 60% 60%, plum, black, orange); |
closest-corner | The gradient is stretched so that it passes through the corner of the element closest to the center (the size is calculated based on the distance to the nearest corner of the element). background-image: radial-gradient(circle closest-corner at 60% 50%, plum, black, orange); background-image: radial-gradient(ellipse closest-corner at 60% 50%, plum, black, orange); |
farthest-side | The gradient is calculated based on the distance to the far side of the element from its center for round gradients ( x axis or y axis) and to the nearest parties ( x axis And y axis) if the gradient is in the shape of an ellipse. background-image: radial-gradient(circle farthest-side at 100% 50%, plum, black, orange); background-image: radial-gradient(ellipse farthest-side at 100% 50%, plum, black, orange); |
farthest-corner | The gradient is stretched so that it passes through the corners of the element farthest from the center (the size is calculated depending on the distance to the far corner of the element). This is the default value. background-image: radial-gradient(circle farthest-corner at 60% 60%, plum, black, orange); background-image: radial-gradient(ellipse farthest-corner at 60% 60%, plum, black, orange); |
Size
Sets the size of the gradient shape. There is no need to specify the circle or ellipse values, It is forbidden to use keywords if the size is specified. If you specify one value, then it will be regarded by the browser as . If you specify two meanings, That first value will be considered by the browser as horizontal radius, A second meaning How vertical radius for elliptical element .
I draw your attention to the fact that You are not allowed to use percentage values if you specify only one value(radius for round element), when used two meanings(for elliptical gradient) It is allowed to indicate these values as percentages.
Position
The starting position of the radial gradient is determined by the -center keyword, but can be changed using units of length(For example: px or em), percentage values And keywords, which are used in CSS property background-position , it is responsible for the position (position) of the background image.
Meaning | Description |
---|---|
left top left center left bottom right top right center right bottom center top center center center bottom | Sets the position of the image. The first value is the horizontal position and the second value is the vertical position. If you specify only one keyword, the other value would be "center" |
x%y% | 0% 0%
(this is the default value). In the lower right corner 100% 100%.
If only one value is specified, then the other value will be 50%.
![]() |
x y | Sets the position of the image. The first value is the horizontal position and the second value is the vertical position. The upper left corner has 0 0. Values can be in pixels, or other CSS units. If only one value is specified, then the other value will be 50%. You can share interest And units. |
Color
It is allowed to use not only “Predefined colors”, but also any “” - hexadecimal (HEX), RGB/-A and HSL/-A color values .
Stop
Values stopping points (color stops ) are specified in length units(For example - px or em) and in percentage values . The breakpoint tells the browser that the radial gradient should reach specified color To set value and smoothly move to the next color, if there is one.
Usage example
Let's look at radial gradients of circular and elliptical shapes and see what their difference is in the following practical example:
In this example, we created four blocks and gave them radial gradients. The upper blocks have elliptical shape, and the lower blocks round shape.
Let's look at an example of positioning a radial gradient.
In this example we created six blocks with different shapes of gradients (circular and elliptical) and positioned the gradient for each block differently, indicating the values in pixels, percent and using keywords.
Please note that if a radial gradient is positioned centered by default and the element is square in shape, then you will not see a difference between a circular gradient and an ellipse-shaped gradient.
Let's look at an example of using radial gradient stop points:
In this example we created six blocks: three upper blocks differ from three lower only by gradient shape, the key points are the same:
- First and fourth block – two color gradient Red color, which smoothly turns into green, occupying the remainder of the element.
- Second and fifth block – three color gradient, in which 10% of the center is occupied Red color, which smoothly turns into green, with a stopping point of 50%, it in turn smoothly transitions to blue, which takes up the rest of the element.
- Third and sixth block – three color gradient, in which 50% of the center is occupied Red color, which smoothly turns into green, with a stopping point of 85%, it in turn smoothly transitions into blue, which takes up the entire remaining small part of the element.
Let's look at how to control the size of a radial gradient in CSS.
In this example, we created three blocks:
First block- we indicated one value 50px , which was interpreted by the browser as radius for circular gradient. Specified for gradient 7 colors. Notice that the outermost color fills the remaining area.
Second block- we indicated two meanings in percentages : first value - horizontal radius, A second meaning - vertical radius for an elliptical gradient. Specified for gradient 8 colors. Please note that we specified white as the final color, which filled the remaining area(one option is to leave only the gradient shape).
Third block- we indicated two meanings in length units (px And em): first value - horizontal radius, A second meaning - vertical radius for an elliptical element. Specified for gradient 7 colors.
Radial Gradient- gradient for creating effects when one color transitions to another. Unlike a linear gradient, this one uses either a circular or an ellipse-shaped transition. The direction of color change goes in different directions from the center. A radial gradient is also called a "circular gradient".
The radial gradient is set using the radial-gradient property in conjunction with background . It has quite a few parameters, which we will consider sequentially.
CSS radial-gradient syntax
background : radial-gradient ( color1, color2,...);
- position - initial coordinates X and Y (most often specified as a percentage). There are constants:
- top - top center (50% 0%)
- left top - top left corner (0% 0%)
- right top - top right corner (100% 0%)
- center (default) - center of the area (50% 50%)
- left center - left center (0% 50%)
- right center - right center (100% 50%)
- bottom - bottom center (50% 100%)
- left bottom - bottom left (0% 100%)
- right bottom - bottom right (100% 100%)
- shape - specifying the shape of the gradient. There are two options:
- circle - circle
- ellipse - ellipse
- size - how the gradient will stretch. Can take the following values
- closest-side - the gradient goes to the closest border of the element.
- closest-corner - the gradient tends to the closest corner.
- farthest-side (default) - The gradient extends to the far edge of the element.
- closest-corner - the gradient extends to the farthest corner of the element.
- color1 - initial color
- color2 - final color
Color can be set in RGB format, a specific color or in rgba format (see html color codes for the site).
Note 1You can specify the transition of several colors separated by commas.
In the very simple version Only two colors can be specified. For example
background : radial-gradient (#ADFF2F, #006400 )Note 2
For browsers, you need to set this property with vendor prefixes: -moz-, -webkit-, -ms-, -o-:
background : -moz-radial-gradient background : -webkit-radial-gradient background : -ms-radial-gradient background : -o-radial-gradientNote 3
The radial-gradient property can also be made repeating: repeating-radial-gradient
background : repeating-radial-gradient ( circle, #8FBC8F, #8FBC8F .5em, transparent .5em, transparent 1.5em);
Examples with radial gradients
Example 1. Different starting position
Using the at keyword, you can specify the position of the center of the radial gradient.
Пример 2. Размер градиента
Ниже представлен пример, который показывает работу границы
На странице преобразуется в следующее
When we talk about gradients, it"s worth beginning with the fact that gradients are an image replacement in CSS. That"s a fancy way of saying that creating a gradient in CSS provides the browser with instructions for painting an image on the screen rather than you providing the browser with the source URL of a file you created in an image editing application, like Photoshop or Sketch. It"s a native CSS way for doing the same thing in code and, as such, gradients are included in the CSS Image Values and Replaced Content specification .
You can see how that gradient assumes the shape is ellipse . That"s because the element itself is not a perfect square. In that case, it would have assumed a circle instead. Pretty smart! Here"s what would happen if we had explicitly declared circle as the shape value:
Gradient { background-image: radial-gradient(circle, yellow, #f06d06); }
Notice the gradient is circular, but only fades all the way to the ending color along the farthest edge. Now we can explicitly declare the position value to ensure that the fade ends by the "closest-side" of the shape instead, like this:
Gradient { background-image: radial-gradient(circle closest-side, yellow, #f06d06); }
The possible values there are: closest-corner , closest-side , farthest-corner , farthest-side . You can think of it like: "I want this radial gradient to fade from the center point to the __________ , and everywhere else fills in to accommodate that."
A radial gradient doesn"t have to start at the default center either, you can specify a certain point by using "at ______ " as part of the first parameter, like:
Gradient { background-image: radial-gradient(circle at top right, yellow, #f06d06); }
I"ll make it more obvious here by making the example a square and adjusting a color-stop:
Browser Support
Browser support for radial-gradient() is largely the same as . The exception is a very old version of Opera. Right when they started supporting gradients they only accounted for linear and not radial.
But similar to linear-gradient() , if your browser support needs to go super deep, then you might consider using or a similar tool that handles vendor prefixing for you rather than having to manage those yourself.
This browser support data is from
CSS не ограничивается линейными градиентами. В вашем распоряжении есть и радиальный градиент, который устанавливается соответствующей функцией radial-gradient() .
Поскольку о синтаксисе градиентных функций мы уже достаточно рассказали в предыдущих уроках, то сейчас нам уже нет необходимости на нем задерживаться - параметры здесь аналогичны radial-gradient() , вы меняете только имя функции.
Background-image: radial-gradient(#5b4ffc, #df02cd);
Позиционирование
Начальная точка вектора радиального градиента находится в центре эллиптической формы (который в свою очередь по умолчанию размещается в центре стилизуемого элемента), откуда градиент расходится кругами. Центр можно смещать, пользуясь теми же значениями, которые принимает background-position . Перед указанием позиции следует использовать приставку at:
Background-image: radial-gradient(at top left, #5b4ffc, #df0253);
Форма и радиус
Форма радиального градиента может быть круглой либо эллиптической. Определить форму можно с помощью указания радиуса либо одного из ключевых слов:
- ellipse - градиент эллиптической формы (значение по умолчанию);
- circle - градиент круглой формы.
Значение радиуса может быть указано в любых доступных единицах CSS. Если указать одно значение, то оно будет принято за радиус круга. Два значения интерпретируются как радиус эллипса по оси X и радиус по оси Y . По умолчанию радиальным градиентом полностью заполняется фон элемента.
Background-image: radial-gradient(ellipse 180px 90px, #a09af1, #000038);
Размер
Существует несколько ключевых слов для управления размерами радиального градиента. Давайте рассмотрим более подробно каждое из них:
![](https://i0.wp.com/idg.net.ua/blog/wp-content/uploads/radial-gradient-closest-side.png)
Опорные точки
В точности как и с линейным градиентом, для создания многоцветного радиального градиента можно добавлять несколько опорных цветовых точек с указанием расстояния:
Background-image: radial-gradient(#144bf1 30%, #3ee9ca 60%, #0a38e5);
Поддержка браузерами
По аналогии с linear-gradient() , если вы собираетесь внедрять функцию radial-gradient() в свой проект, стоит дополнить код CSS объявлениями с упоминанием вендорных префиксов, а также указать резервный цветовой фон для старых браузеров IE.
Далее в учебнике: repeating-radial-gradient() - повторяющийся радиальный градиент.
Рис. 1. Радиальный и линейный градиент
Радиальный градиент создаётся с помощью свойства background или background-image .
Синтаксис
background-image: radial-gradient([ circle || <радиус> ] [ at <позиция> ]? , | [ ellipse || [<радиус> | <проценты> ]{2}] [ at <позиция> ]? , | [ [ circle | ellipse ] || <размер> ] [ at <позиция> ]? , | at <позиция> , <цвет> [ , <цвет> ]*)
Обозначения
Описание | Пример | |
---|---|---|
<тип> | Указывает тип значения. | <размер> |
A && B | Значения должны выводиться в указанном порядке. | <размер> && <цвет> |
A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
Группирует значения. | [ crop || cross ] | |
* | Повторять ноль или больше раз. | [,<время>]* |
+ | Повторять один или больше раз. | <число>+ |
? | Указанный тип, слово или группа не является обязательным. | inset? |
{A, B} | Повторять не менее A, но не более B раз. | <радиус>{1,4} |
# | Повторять один или больше раз через запятую. | <время># |
Значения
circle Радиальный градиент круглой формы. ellipse Создаёт градиент эллиптической формы. Эта форма установлена по умолчанию. <радиус> Радиус градиента в доступных для CSS единицах. Одно значение указывает радиус круга, два значения - радиус эллипса по оси x и его же радиус по оси y. Если радиус явно не указан, градиент будет заполнять собой весь фон элемента. <позиция>
Задаёт начальную точку откуда исходит градиент. Позиция точки пишется аналогично значениям свойства background-position с помощью ключевых слов или доступных единиц измерения вроде пикселей или процентов; ниже приведены возможные сочетания.
- top left = left top = 0% 0% (в левом верхнем углу);
- top = top center = center top = 50% 0% (по центру вверху);
- right top = top right = 100% 0% (в правом верхнем углу);
- left = left center = center left = 0% 50% (по левому краю и по центру);
- center = center center = 50% 50% (по центру) - это значение по умолчанию;
- right = right center = center right = 100% 50% (по правому краю и по центру);
- bottom left = left bottom = 0% 100% (в левом нижнем углу);
- bottom = bottom center = center bottom = 50% 100% (по центру внизу);
- bottom right = right bottom = 100% 100% (в правом нижнем углу).
Значение | Код | Описание | Вид |
---|---|---|---|
closest-side | background: radial-gradient(circle closest-side at 30px 20px, #fff, #000); background: radial-gradient(closest-side at 30px 20px, #fff, #000); | Градиент совпадает с ближайшей к нему стороной блока (для круга) или одновременно совпадает с ближайшими горизонтальными и вертикальными сторонами (для эллипса). | ![]() |
background: radial-gradient(circle closest-corner at 30px 20px , #fff, #000); background: radial-gradient(closest-corner at 30px 20px , #fff, #000); | Форма градиента вычисляется на основании информации о расстоянии до ближайшего угла блока. | ![]() |
|
background: radial-gradient(circle farthest-side at 30px 20px , #fff, #000); background: radial-gradient(farthest-side at 30px 20px , #fff, #000); | Похож по своему действию на closest-side , но градиент распространяется до дальней стороны блока. | ![]() |
|
farthest-corner | background: radial-gradient(circle farthest-corner at 30px 20px , #fff, #000); background: radial-gradient(farthest-corner at 30px 20px , #fff, #000); | Форма градиента вычисляется на основании информации о расстоянии до дальнего угла блока, | ![]() |
Пример
Result this example shown below.
Note
Chrome before version 26, Safari before version 6.1, and Android before version 4.4 support -webkit-radial-gradient() .
Opera up to version 12.10 supports -o-radial-gradient() .
Firefox up to version 16 supports -moz-radial-gradient() .
All prefixed properties do not use the at keyword when setting the position of the gradient starting point.
Specification
Each specification goes through several stages of approval.
- Recommendation - The specification has been approved by the W3C and is recommended as a standard.
- Candidate Recommendation ( Possible recommendation ) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
- Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
- Working Draft - A more mature version of a draft that has been discussed and amended for community review.
- Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
- Draft ( Draft specification) - the first draft version of the standard.