Мегафон

Радиальный градиент CSS. Gradients CSS уроки для начинающих академия Круглый градиент

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

Для самого простого градиента достаточно задать только цвета:

Background: radial-gradient(gold, orangered);

По умолчанию центр градиента находится по центру, градиент имеет форму эллипса:

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

Форма (конечная фигура градиента) может быть кругом и эллипсом. По умолчанию - эллипс, градиент стремится занять всё свободное пространство элемента, вытягиваясь, если это необходимо.

Чтобы градиент имел форму круга - это нужно задать явно с помощью ключевого слова circle .

Если форма не задана, но задан размер - одно значение задает радиус круга, если значений два - градиент получает форму эллипса. При наличии размеров явное задание формы градиента игнорируется.

Положение определяет где будет расположен центр градиента. Используются те же ключевые слова, что и для линейного градиента, но с приставкой at: at top , at right , at bottom , at left и at center - значение по умолчанию.

Их так же можно сочетать между собой, чтобы расположить градиент на заданной стороне, например: at right top - в верхнем правом углу.

Ниже можно увидеть как работают разные положения:

Код первого квадрата:

Background: radial-gradient(at top left, purple, crimson, orangered, gold);

Также можно задавать точное положение градиента, например at 20% 50% или at 10px 150px .

Размер определяет размеры конечной фигуры градиента. Для эллиптических градиентов значения можно задавать в процентах, для круглых - нет.

Если задано одно значение - оно считается радиусом круглого градиента. Если задано два значения - первое считается горизонтальным радиусом эллипса, второе - вертикальным.

Ниже примеры круглых и эллиптических градиентов. Форма фигуры определяется заданными размерами:

Также можно использовать ключевые слова:

closest-side - градиент заканчивается у границы элемента ближайшей к центру градиента. Если это эллипс, градиент касается всех границ элемента. farthest-side - градиент заканчивается у дальней границы элемента. Если это эллипс, градиент касается всех границ элемента. closest-corner - конечная фигура растягивается таким образом, чтобы она проходила через угол элемента, ближайший к центру градиента. Если конечная фигура - эллипс, градиент растягивается на всю фигуру. При этом параметре градиент заполняет собой всю фигуру, частично выходя за её пределы. farthest-corner - аналогично closest-corner , только конечная фигура проходит через угол, дальний от центра градиента. Значение по умолчанию.

Некоторым градиентам добавлено положение at bottom , чтобы было лучше видно действие кода:

Радиальный градиент также может быть повторяющимся - это repeating-radial-gradient .

Примерный код:

Background: repeating-radial-gradient(circle, darkkhaki, darkkhaki .5em, transparent .5em, transparent 1.5em);

Как и в случае с линейным градиентом, повторяющийся градиент не очень аккуратно отрисовывается.

Сочетая несколько фонов с разными параметрами можно получить удивительные вещи:

Если при создании узоров использовать относительные единицы (em , %), а не абсоюлютные (px), размер получившихся паттернов потом можно будет легко регулировать изменяя только размер шрифта.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Composition of a radial gradient

A radial gradient is defined by a center point , an ending shape , and two or more color-stop points .

To create a smooth gradient, the radial-gradient() function draws a series of concentric shapes radiating out from the center to the ending shape (and potentially beyond). The ending shape may be either a circle or an ellipse.

Color-stop points are positioned on a virtual gradient ray that extends horizontally from the center towards the right. Percentage-based color-stop positions are relative to the intersection between the ending shape and this gradient ray, which represents 100% . Each shape is a single color determined by the color on the gradient ray it intersects.

Syntax

/* A gradient at the center of its container, starting red, changing to blue, and finishing green */ radial-gradient(circle at center, red 0, blue, green 100%)

Values

(or ) CSS data type denotes a two-dimensional coordinate used to set a location relative to an element box. It is used in the background-position and offset-anchor properties."> The position of the gradient, interpreted in the same way as background-position or transform-origin . If unspecified, it defaults to center . The gradient"s shape. The value can be circle (meaning that the gradient"s shape is a circle with constant radius) or ellipse (meaning that the shape is an axis-aligned ellipse). If unspecified, it defaults to ellipse . A keyword describing how big the ending shape must be. The possible values are:
Keyword Description
closest-side The gradient"s ending shape meets the side of the box closest to its center (for circles) or meets both the vertical and horizontal sides closest to the center (for ellipses).
closest-corner The gradient"s ending shape is sized so that it exactly meets the closest corner of the box from its center.
farthest-side Similar to closest-side , except the ending shape is sized to meet the side of the box farthest from its center (or vertical and horizontal sides).
farthest-corner The default value, the gradient"s ending shape is sized so that it exactly meets the farthest corner of the box from its center.

Note: Early implementations of this function included other keywords (cover and contain) as synonyms of the standard farthest-corner and closest-side , respectively. Use the standard keywords only, as some implementations have already dropped those older variants.

A color-stop"s CSS data type represents a color in the sRGB color space. A may also include an alpha-channel transparency value, indicating how the color should composite with its background."> value, followed by an one or two optional stop positions (either a CSS data type represents a percentage value. It is often used to define a size as relative to an element" s parent object. numerous properties can use percentages such as width height margin padding and font-size.> or a CSS data type represents a distance value. Lengths can be used in numerous CSS properties, such as width, height, margin, padding, border-width, font-size, and text-shadow."> along the gradient"s axis). A percentage of 0% , or a length of 0 , represents the center of the gradient; the value 100% represents the intersection of the ending shape with the virtual gradient ray. Percentage values in between are linearly positioned on the gradient ray. Including two stop positions is equivalent to declaring two color stops with the same color at the two positions. Th color-hint is an interpolation hint defining how the gradient progresses between adjacent color stops. The length defines at which point between two color stops the gradient color should reach the midpoint of the color transition. If omitted, the midpoint of the color transition is the midpoint between two color stops.

Formal syntax

radial-gradient([ [ circle || ] [ at ]? , | [ ellipse || [ | ]{2} ] [ at ]? , | [ [ circle | ellipse ] || ] ? , | at , ]? [ , ]+) where = closest-corner | closest-side | farthest-corner | farthest-side and = [ [, ? ]? ]#, and = [ ]? and = [ | ]{1,2} and = [ | ]

Note that negative "s are not allowed, however browsers had implemented negative lengths which are now being removed. See the Firefox site compat note .

Examples

Simple gradient

Radial-gradient { background-image: radial-gradient(cyan 0%, transparent 20%, salmon 40%); }

Non-centered gradient

.radial-gradient { width: 240px; height: 120px; }

Radial-gradient { background-image: radial-gradient(farthest-corner at 40px 40px, #f35 0%, #43e 100%); }

Specifications

Specification Status Comment
CSS Images Module Level 3
The definition of "radial-gradients()" in that specification.
Candidate Recommendation Initial definition.

Browser compatibility

The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
radial-gradient() Chrome Full support 26 Full support 26 Full support 13

Prefixed

Prefixed
Edge Full support 12 Firefox Full support 16

Notes

Full support 16

Notes

Notes Before Firefox 36, gradients weren"t applied on the pre-multiplied color space, leading to shades of grey unexpectedly appearing when used with transparency. Full support 3.6

Prefixed Notes

Prefixed

Prefixed

Prefixed

Prefixed Disabled

Prefixed
IE Full support 10

Notes

Full support 10

Notes

Notes Internet Explorer 5.5 through 9.0 supported gradients via a proprietary filter: .
Opera Full support 12.1 Full support 12.1 No support 11.6 - 15

Prefixed

Prefixed Full support 15

Prefixed

Prefixed Implemented with the vendor prefix: -webkit-
Safari Full support 6.1 Full support 6.1 Full support 5.1

Prefixed Notes

Prefixed -webkit-gradient(radial,…)
WebView Android Full support ≤37 Full support ≤37 Full support ≤37

Prefixed

Prefixed Implemented with the vendor prefix: -webkit-
Chrome Android Full support 26 Full support 26 Full support 18

Prefixed

Prefixed Implemented with the vendor prefix: -webkit-
Firefox Android Full support 16

Notes

Full support 16

Notes

Notes Before Firefox 36, gradients weren"t applied on the pre-multiplied color space, leading to shades of grey unexpectedly appearing when used with transparency. Full support 4

Prefixed Notes

Prefixed Implemented with the vendor prefix: -moz- Notes Since Firefox 42, the prefixed version of gradients can be disabled by setting layout.css.prefixes.gradients to false . Full support 49

Prefixed

Prefixed Implemented with the vendor prefix: -webkit- Full support 44

Prefixed Disabled

Prefixed Implemented with the vendor prefix: -webkit- Disabled From version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support 12.1 Full support 12.1 No support 12 - 14

Prefixed

Prefixed Implemented with the vendor prefix: -o- Full support 14

Prefixed

Prefixed Implemented with the vendor prefix: -webkit-
Safari iOS Full support 6.1 Full support 6.1 Full support 6

Prefixed Notes

Prefixed Implemented with the vendor prefix: -webkit- Notes Safari 4 was supporting an experimental -webkit-gradient(radial,…) function. This old outdated syntax is still supported for compatibility purposes.
Samsung Internet Android Full support 1.5 Full support 1.5 Full support 1.0

Prefixed

Prefixed Implemented with the vendor prefix: -webkit-
at syntax Chrome Full support 26 Edge Full support 12 Firefox Full support 16

Notes

Full support 16

Notes

Notes Before Firefox 36, gradients weren"t applied on the pre-multiplied color space, leading to shades of grey unexpectedly appearing when used with transparency. Full support 10

Prefixed Notes

Prefixed Implemented with the vendor prefix: -moz- Notes Since Firefox 42, the prefixed version of gradients can be disabled by setting layout.css.prefixes.gradients to false . Full support 49

Prefixed

Prefixed Implemented with the vendor prefix: -webkit- Full support 44

Prefixed Disabled

Prefixed Implemented with the vendor prefix: -webkit- Disabled From version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE Full support 10 Opera Full support 15 Full support 15 No support 11.6 - 15

Prefixed

Prefixed Implemented with the vendor prefix: -o-
Safari No support No WebView Android Full support ≤37 Chrome Android Full support 26 Firefox Android Full support 16 Full support 16 Full support 10

Prefixed

Prefixed Implemented with the vendor prefix: -moz-
Opera Android Full support 14 Full support 14 No support 12 - 14

Prefixed

Prefixed Implemented with the vendor prefix: -o-
Safari iOS No support No Samsung Internet Android Full support 1.5
Double-position color stops Chrome Full support 71 Edge Full support 79 Firefox Full support 64 IE No support No Opera Full support 58 Safari Full support 12.1 WebView Android Full support 71 Chrome Android Full support 71 Firefox Android Full support 64 Opera Android Full support 50 Safari iOS Full support 12.2 Samsung Internet Android Full support 10.0
Interpolation Hints / Gradient Midpoints Chrome Full support 40 Edge Full support 79 Firefox Full support 36 IE No support No Opera Full support 27 Safari Full support 6.1 WebView Android Full support 40 Chrome Android Full support 40 Firefox Android Full support 36 Opera Android Full support 27 Safari iOS Full support 6.1 Samsung Internet Android Full support 4.0

Legend

Full support Full support No support No support See implementation notes. See implementation notes. User must explicitly enable this feature. User must explicitly enable this feature. Requires a vendor prefix or different name for use.

Quantum CSS notes

Gecko used to have a long-standing bug whereby radial gradients like radial-gradient(circle gold,red) would work, even though they shouldn"t because of the missing comma between circle and gold . Also,

CSS-градиент представляет собой переходы от одного цвета к другому.

Градиенты создаются с помощью функций linear-gradient() и radial-gradient() .

Градиентный фон можно устанавливать в свойствах background , background-image , border-image и list-style-image .

Как сделать градиент в CSS

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

IE: 10.0
Firefox: 16, 3.6 -moz-
Chrome: 26.0, 10.0 -webkit-
Safari: 6.1, 5.1 -webkit-
Opera: 12.1, 11.1 -o-
iOS Safari: 7.1
Opera Mini:
Android Browser: 4.4, 4.1 -webkit-
Chrome for Android: 44

1. Линейный градиент linear-gradient()


Рис. 1. Линия градиента, начальная и конечная точки и угол градиента

Линейный градиент создается с помощью двух и более цветов, для которых задано направление, или линия градиента .

Если направление не указано, используется значение по умолчанию — сверху-вниз .

Цвета градиента по умолчанию распределяются равномерно в направлении, перпендикулярном линии градиента.

Background: linear-gradient(угол / сторона или угол наклона с помощью ключевого слова (пары ключевых слов), первый цвет, второй цвет и т.д.);

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

Div { height: 200px; background: linear-gradient(45deg, #EECFBA, #C5DDE8); }

с помощью ключевых слов to top , to right , to bottom , to left , которые соответствуют углу градиента, равному 0deg , 90deg , 180deg и 270deg соответственно.

Div { height: 200px; background: linear-gradient(to right, #F6EFD2, #CEAD78); }

Если направление задано парой ключевых слов, например, to top left , то начальная точка градиента будет расположена в противоположном направлении, в данном случае справа внизу.

Div { height: 200px; background: linear-gradient(to top left, powderblue, pink); }

Для неравномерного распределения цветов указывается начальная позиция каждого цвета через точки остановки градиента, так называемые color stops . Точки остановки задаются в % , где 0% — начальная точка, 100% — конечная точка, например:

Div { height: 200px; background: linear-gradient(to top, #E4AF9D 20%, #E4E4D8 50%, #A19887 80%); }

Для чёткого распределения цветных полос каждый последующий цвет нужно начинать с точки остановки предыдущего цвета:

Div { height: 200px; background: linear-gradient(to right, #FFDDD6 20%, #FFF9ED 20%, #FFF9ED 80%, #DBDBDB 80%); }

2. Радиальный градиент radial-gradient()

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

Background: radial-gradient(форма градиента / размер / позиция центра, первый цвет, второй цвет и т.д.);

Форма градиента определяется ключевыми словами circle или ellipse . Если форма не задана, по умолчанию радиальный градиент принимает форму эллипса.

Div { height: 200px; background: radial-gradient(white, #FFA9A1); }

Позиция центра задаётся с помощью ключевых слов, используемых в свойстве background-position , с добавлением приставки at . Если позиция центра не задана, используется значение по умолчанию at center .

Div { height: 200px; background: radial-gradient(at top, #FEFFFF, #A7CECC); }

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

Div { height: 200px; background: radial-gradient(40% 50%, #FAECD5, #CAE4D8); }

Размер градиента задаётся с помощью ключевых слов. Значение по умолчанию farthest-corner (к дальнему углу).

div { height: 200px; background: radial-gradient(circle farthest-corner at 100px 50px, #FBF2EB, #352A3B); }

С помощью радиального градиента можно создавать реалистичные объёмные фигуры, такие как мячи, кнопки.

Мяч

div { width: 200px; height: 200px; border-radius: 50%; margin: 0 auto; background: radial-gradient(circle at 65% 15%, aqua, darkblue); }

Кнопка

.wrap { height: 200px; padding: 50px 0; background: #cccccc; } .button { width: 100px; height: 100px; border-radius: 50%; margin: 0 auto; background: radial-gradient(farthest-side ellipse at top left, white, #aaaaaa); box-shadow: 5px 10px 20px rgba(0,0,0,0.3), -5px -10px 20px rgba(255,255,255,0.5); }

Почтовая марка


Используя в градиентах прозрачный цвет, можно создавать вот такие эффекты.

Jpg">