radial gradient. Gradients CSS tutorials for beginners academy Circular gradient css

radial gradient- a gradient to create effects when one color transitions to another. Unlike a linear gradient, either a circular or elliptical transition is used here. 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 along with background . It has quite a few parameters, which we will consider in sequence.

CSS Syntax radial-gradient

background : radial-gradient ( color1, color2,...);
  • position - the initial X and Y coordinates (most often set 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) - area center (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%)
    The at keyword is required.
  • shape - set the shape of the gradient. There are two options:
    • circle - circle
    • ellipse - ellipse
  • size - how the gradient will be stretched. Can take the following values
    • closest-side - The gradient tends to the closest edge of the element.
    • closest-corner - The gradient tends to the nearest corner.
    • farthest-side (default) - The gradient extends to the farthest side of the element.
    • closest-corner - The gradient extends to the element's far corner.
    Below is a table with examples
  • color1 - start color
  • color2 - final color

The color can be set in RGB format, a specific color or in rgba format (see html color codes for the site).

Note 1

You can set 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-gradient
Note 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 start position

The at keyword can be used to set the position of the center of the radial gradient.

Пример 2. Размер градиента

Ниже представлен пример, который показывает работу границы

На странице преобразуется в следующее

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 - градиент круглой формы.
background-image: radial-gradient(circle, #5b4ffc, #df0253);

Значение радиуса может быть указано в любых доступных единицах CSS. Если указать одно значение, то оно будет принято за радиус круга. Два значения интерпретируются как радиус эллипса по оси X и радиус по оси Y . По умолчанию радиальным градиентом полностью заполняется фон элемента.

Background-image: radial-gradient(ellipse 180px 90px, #a09af1, #000038);

Размер

Существует несколько ключевых слов для управления размерами радиального градиента. Давайте рассмотрим более подробно каждое из них:


Опорные точки

В точности как и с линейным градиентом, для создания многоцветного радиального градиента можно добавлять несколько опорных цветовых точек с указанием расстояния:

Background-image: radial-gradient(#144bf1 30%, #3ee9ca 60%, #0a38e5);

Поддержка браузерами

По аналогии с linear-gradient() , если вы собираетесь внедрять функцию radial-gradient() в свой проект, стоит дополнить код CSS объявлениями с упоминанием вендорных префиксов, а также указать резервный цветовой фон для старых браузеров IE.

Далее в учебнике: repeating-radial-gradient() - повторяющийся радиальный градиент.

При разработке дизайна проекта бывают случаи, когда необходимо создать градиент на сайте , то есть плавный переход цвета из одного в другой. Раньше сделать это стандартными средствами была проблематично, но с появлением CSS3 стало возможным делать градиенты быстро и просто.

Для получения эффекта градиента нередко можно увидеть использование специальных картинок, на которых создан градиент в графическом редакторе. Но это не самый практичный способ, плюс лишняя загрузка картинки на сайте, что само по себе уменьшает скорость загрузки сайта. А если таких картинок много, тогда все еще хуже. Поэтому нужно было что-то с этим делать.

Градиент может часто пригодиться на любом сайте, поэтому в CSS3 было решено добавить функционал для создания таких градиентов. Различают линейный и радиальный градиенты . На рисунке выше, слева – линейный, справа – радиальный градиент. Если вдруг браузер не будет поддерживать градиент, то для этого в файле стилей выше строки задания градиента, следует указать простой фон для элемента.

Для создания линейного градиента существует значение linear-gradient , для радиального radial-gradient . Кроме того, существуют две функции для повтора градиента repeating-linear-gradient и repeating-radial-gradient . Отдельного свойства для добавления градиента не предусмотрено, он считается фоновым изображением, поэтому добавляется через свойства:

  • background,
  • background-image,
  • border-image,
  • list-style-image.

Рассмотрим примеры создания градиентов. Градиент создается при помощи соответствующей функции и ее параметров. Первый параметр функции – это позиция, можно использовать ключевые слова. Второй и третий параметры - это значение цвета и его положение в градиенте.

To indicate a position, first write to and then the keywords are added top, bottom, left, right and their combinations, word order is not important. Also, instead of a keyword, you can set the slope of the gradient line, showing the direction of the gradient. First, a positive or negative value of the angle is written, after which deg, example - 30deg.

To create a complex gradient, you need more than 2 colors - CSS3 allows you to add unlimited quantity colors separated by commas. You can apply transparent and translucent colors. For precise positioning of a color in a gradient, after the color value, its position is indicated in percentages, pixels, or other units.

As for radial gradients, they are similar to linear gradients. What is the difference between linear and radial gradient? The fact that in radial one color passes into another like circles on water around a point, and not along a straight line. There are two forms of radial gradient: circle(circle) and ellipse(ellipse). They differ appearance, the default shape is ellipse. Also with the shape of the gradient, you can set its size, depending on the keywords used - the size is indicated with a space after the gradient shape.

You can see in detail the possible values ​​of the parameters of these functions in the developer console by specifying desired function– then expand the list of values ​​by clicking on the arrow.

In this way, create a gradient with using CSS everyone can. With the help of gradients, you can make unique elements on the site, for example, using gradients and the property background-size you can get different background pictures without using images. But developing gradients yourself may not be very convenient, so there are ready-made services for generating gradient code on the network.

A radial gradient extends from the center point of the gradient in all directions in a circle or ellipse (default shape), showing a smooth transition from one color hue to another. A radial gradient is created using the radial-gradient() function. The function creates an image that is a radial gradient between the specified shades of colors. By default, the size of the gradient matches the size of the element it is applied to.

The radial-gradient() function takes the following comma-separated arguments:

  • The first argument is CSS keywords and/or units that define the final shape, size, and starting position of the gradient. Optional argument.
  • A comma-separated list of two or more colors, each of which may be followed by a stop position.

The simplest radial gradient requires only two arguments specifying a start and end color:

Div ( background-image: radial-gradient(cyan, indigo); width: 400px; height: 100px; ) Try »

As with linear gradients, a radial gradient can include a list of more than two colors, and any color can have a stop position.

Div ( width: 400px; height: 100px; margin: 10px; ) #one ( background-image: radial-gradient(cyan, yellow, indigo, white); ) #two ( background-image: radial-gradient(cyan, yellow 10%, indigo 30%, white 50%); ) Try »

The shape of a radial gradient can be defined using the keywords circle (circle) and ellipse (ellipse), specifying one of them as the first argument:

Div ( width: 400px; height: 100px; margin: 10px; ) #one ( background-image: radial-gradient(ellipse, cyan, indigo); ) #two ( background-image: radial-gradient(circle, cyan, indigo ); ) Try »

By default, the browser places the center point of the radial gradient at the center of the element. The center of the gradient can be positioned using the at keyword followed by the keywords (top, left, right, bottom, center) or values ​​in the specified CSS units:

Meaning Description
left top
left center
left bottom
right top
right center
right bottom
center top
center center
center bottom
If you specify only one keyword, the second one will be "center".
x%y% The first value is the horizontal position, the second value is the vertical position. The top left corner is the 0% 0% position. The bottom right corner is the 100% 100% position. If you specify only one value, the other value will be 50%.
x-pos y-pos The first value is the horizontal position, the second is the vertical position. The top left corner is position 0 0. Units can be pixels (0px 0px) or any other CSS unit. If you specify only one value, the other value will be 50%. You can combine % and units.

The positioning of the gradient is specified before the hue values, but after the gradient shape keyword (if any):

Div ( width: 400px; height: 100px; margin: 10px; ) #one ( background-image: radial-gradient(at right, cyan, indigo); ) #two ( background-image: radial-gradient(circle at 300px 50px , cyan, indigo, yellow); ) #three ( background-image: radial-gradient(circle at top left, cyan, indigo, yellow); ) Try »

The size of the gradient (how big the final shape of the gradient should be) can be specified using one of four key phrases or specifying the radius using CSS units (you can't use percentages to define the radius).

Keywords Description
The final size of the gradient depends on the distance between the center of the gradient and the side of the element closest to it (for a circle) or on the distance between the center and the two sides of the element closest to it (for an ellipse).
The final size of the gradient depends on the distance between the center of the gradient and the nearest corner of the element.
The final size of the gradient depends on the distance between the center of the gradient and the side of the element farthest from it (for a circle) or the distance between the center of the gradient and the two sides farthest from it (for an ellipse).
The final size of the gradient depends on the distance between the center of the gradient and the corner of the element farthest from it. Used by default for a circle or ellipse shape.

Keywords defining the size of the gradient or the radius are specified before or after the keyword defining the shape, and always before the position.

Div ( width: 400px; height: 100px; margin: 10px; ) #one ( background-image: radial-gradient(circle closest-corner at 100px, cyan 50%, indigo); ) #two ( background-image: radial- gradient(circle closest-side, cyan, red, indigo); ) #three ( background-image: radial-gradient(100px circle at 200px, cyan 50%, indigo); ) #four ( background-image: radial-gradient( 170px 50px ellipse at 175px, cyan, #90EE90, rgba(172,160,160,0)); )

Rice. 1. Radial and linear gradient

A radial gradient is created using the background or background-image property with the radial-gradient parameter. In the simplest case, to set a radial gradient, you need only two parameters: the start and end color. By default, the starting point is located in the center. Example 1 shows how to create some kind of ball, using a radial gradient and rounded corners.

Example 1 Gradient

Gradient

Result this example shown in fig. 1. Please note that the example works correctly in IE10 and Opera 12, earlier versions of these browsers do not support radial gradients, and does not work in Safari 5.1, which requires the -webkit prefix.

Rice. 2. Radial Gradient

The starting point of the gradient can be set anywhere in the element, for this, its position is first specified.

The position of a point is written in the same way as background-position property values, using keywords or available units such as pixels or percentages; possible combinations are listed below.

  • at top left = at left top = at 0% 0% (in the left upper corner);
  • at top = at top center = at center top = at 50% 0% (centered on top);
  • at right top = at top right = at 100% 0% (top right corner);
  • at left = at left center = at center left = at 0% 50% (left and center);
  • at center = at center center = at 50% 50% (centered) is the default value;
  • at right = at right center = at center right = at 100% 50% (right and center);
  • at bottom left = at left bottom = at 0% 100% (bottom left corner);
  • at bottom = at bottom center = at center bottom = at 50% 100% (centered at the bottom);
  • at bottom right = at right bottom = at 100% 100% (in the bottom right corner).

If we set the position of the starting point for example 1 to be at 40px 45px, and make the second color slightly darker (#0076a5), we get a slightly more realistic ball (Fig. 3).

Rice. 3. Change the starting point of the gradient

There are two forms of a radial gradient - a circle (circle) and an ellipse (ellipse), which differ in their appearance. The default is an elliptical gradient.

The difference between the circular and elliptical gradient for colors #f9e497 and #ffb60f is shown in fig. four.

Rice. 4. Different types of gradient

For an element whose width is equal to the height, as in the balloon example, the difference between the gradient types will not be noticeable.

Example 2 shows how to create a circular gradient with a given starting point. Three color values ​​are used to enhance contrast between colors instead of two.

Example 2: Circular Gradient

HTML5 CSS3 IE 9 IE 10 Cr Op Sa Fx

Gradient

This element helps when you are aware of the fact that you do not understand at all who and how can help you. It is at this moment that we suggest that no one can help you.

Pay attention to the syntax, if we want to combine the shape of the gradient with the indication of the starting point, then the circle keyword comes first, and then the position separated by a space. The result of this example is shown in Fig. 5.

Rice. 5. Circular Gradient

Along with the type of the gradient, you can also set its size, which depends on the keywords used. The size is written with a space after the gradient type (circle or ellipse).

In table. 1 lists the possible size values ​​with their description and result for white and black. The code and view is given for a circular and elliptical gradient.

Tab. 1. Keywords for resizing the gradient
Meaning The code Description View

background: radial-gradient(circle closest-side at 30px 20px, #fff, #000);

background: radial-gradient(ellipse closest-side at 30px 20px, #fff, #000);

The shape of the gradient matches the block side closest to it.

background: radial-gradient(circle closest-corner at 30px 20px, #fff, #000);

background: radial-gradient(ellipse closest-corner at 30px 20px, #fff, #000);

The shape of the gradient is calculated based on information about the distance to the nearest corner of the block.

background: radial-gradient(circle farthest-side at 30px 20px, #fff, #000);

background: radial-gradient(ellipse farthest-side at 30px 20px, #fff, #000);

The gradient extends to the far side of the block.
farthest-corner

background: radial-gradient(circle farthest-corner at 30px 20px, #fff, #000);

background: radial-gradient(ellipse farthest-corner at 30px 20px, #fff, #000);

The shape of the gradient is calculated based on information about the distance to the far corner of the block,

For the central starting point, the gradients seem to match. But the gradients will be different if you set the starting point at the corner. Example 3 uses a value that specifies the starting point in pixels.

Example 3 Gradient Size

HTML5 CSS3 IE 9 IE 10 Cr Op Sa Fx

Gradient

Content

The result of this example is shown in Fig. 6.

Rice. 6. Using the closest-corner value

Like a linear gradient, you can specify multiple colors, set their position, and make sharp transitions between colors. To do this, an arbitrary number of colors is listed separated by commas, and after the color value, a space is followed by its position, which can be specified in pixels or percentages. The extreme values ​​of 0% and 100% can be omitted, they are assumed automatically.

Sharp transitions are obtained when the position of one color coincides with the position of another, as shown in example 4. The difference of one pixel is done to smooth the transition a little, otherwise it turns out to be a "ladder" of pixels, which does not look very nice.

Example 4. Abrupt transitions

HTML5 CSS3 IE 9 IE 10 Cr Op Sa Fx

Gradient

The result of this example is shown in Fig. 7.

Rice. 7. Sharp transitions between different colors

If the linear and radial gradient are complemented with the background-size property, then we will get a wide variety of repeating background pictures that are made without the use of images.

Internet