Css радиальный градиент. Gradients CSS уроки для начинающих академия. Использование нескольких цветовых остановок

Рис. 1. Радиальный и линейный градиент

Радиальный градиент создаётся с помощью свойства background или background-image с параметром radial-gradient . В простейшем случае для задания радиального градиента понадобится всего два параметра: начальный и конечный цвет. По умолчанию, начальная точка располагается при этом в центре. В примере 1 показано создание некоторого подобия шарика, для этого используется радиальный градиент и скругление углов.

Пример 1. Градиент

Градиент

Результат данного примера показан на рис. 1. Обратите внимание, что пример корректно работает в IE10 и Opera 12, ранние версии этих браузеров не поддерживают радиальные градиенты, и не работает в Safari 5.1, который требует наличие префикса -webkit.

Рис. 2. Радиальный градиент

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

Позиция точки пишется аналогично значениям свойства background-position с помощью ключевых слов или доступных единиц измерения вроде пикселов или процентов; ниже приведены возможные сочетания.

  • at top left = at left top = at 0% 0% (в левом верхнем углу);
  • at top = at top center = at center top = at 50% 0% (по центру вверху);
  • at right top = at top right = at 100% 0% (в правом верхнем углу);
  • at left = at left center = at center left = at 0% 50% (по левому краю и по центру);
  • at center = at center center = at 50% 50% (по центру) — это значение по умолчанию;
  • at right = at right center = at center right = at 100% 50% (по правому краю и по центру);
  • at bottom left = at left bottom = at 0% 100% (в левом нижнем углу);
  • at bottom = at bottom center = at center bottom = at 50% 100% (по центру внизу);
  • at bottom right = at right bottom = at 100% 100% (в правом нижнем углу).

Если задать позицию начальной точки для примера 1 как at 40px 45px, а второй цвет сделать несколько темнее (#0076a5), то получится чуть более реалистичный шарик (рис. 3).

Рис. 3. Изменение начальной точки градиента

Возможны две формы радиального градиента - круг (circle) и эллипс (ellipse), которые различаются своим видом. По умолчанию устанавливается эллиптический градиент.

Разница между круговым и эллиптическим градиентом для цветов #f9e497 и #ffb60f продемонстрирована на рис. 4.

Рис. 4. Разные виды градиента

Для элемента, у которого ширина равна высоте, как в примере с шариком, разница между типами градиента будет незаметна.

В примере 2 показано создание кругового градиента с заданной начальной точкой. Для усиления контрастности между цветами используется три значения цвета, а не два.

Пример 2. Круговой градиент

HTML5 CSS3 IE 9 IE 10 Cr Op Sa Fx

Градиент

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

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

Рис. 5. Круговой градиент

Наряду с типом градиента можно задавать и его размер, который зависит от применяемых ключевых слов. Размер пишется через пробел после типа градиента (circle или ellipse).

В табл. 1 перечислены возможные значения размера с их описанием и результатом для белого и чёрного цвета. Код и вид дан для кругового и эллиптического градиента.

Табл. 1. Ключевые слова для изменения размера градиента
Значение Код Описание Вид

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

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

Форма градиента совпадает с ближайшей к нему стороной блока.

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

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

Форма градиента вычисляется на основании информации о расстоянии до ближайшего угла блока.

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

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

Градиент распространяется до дальней стороны блока.
farthest-corner

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

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

Форма градиента вычисляется на основании информации о расстоянии до дальнего угла блока,

Для центральной начальной точки градиенты вроде и совпадают. Но градиенты будут различаться, если установить начальную точку в углу. В примере 3 используется значение с заданием начальной точки в пикселах.

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

HTML5 CSS3 IE 9 IE 10 Cr Op Sa Fx

Градиент

Содержимое

Результат данного примера показан на рис. 6.

Рис. 6. Использование значения closest-corner

Подобно линейному градиенту можно указывать несколько цветов, устанавливать их позицию и делать резкие переходы между цветами. Для этого произвольное количество цветов перечисляется через запятую, а после значения цвета через пробел идёт его позиция, которая может быть задана в пикселах или процентах. Крайние значения 0% и 100% можно не писать, они подразумеваются автоматически.

Резкие переходы получаются, когда позиция одного цвета совпадает с позицией другого, как показано в примере 4. Разница в один пиксел сделана, чтобы немного сгладить переход, иначе получается «лесенка» из пикселов, что смотрится не очень красиво.

Пример 4. Резкие переходы

HTML5 CSS3 IE 9 IE 10 Cr Op Sa Fx

Градиент

Результат данного примера показан на рис. 7.

Рис. 7. Резкие переходы между разными цветами

Если линейный и радиальный градиент дополнить свойством background-size , тогда мы получим самые разнообразные повторяющиеся фоновые картинки, которые сделаны без использования изображений.

Градиентный фон

Градиенты CSS позволяют отображать плавные переходы между двумя или более указанными цветами.

CSS определяет два типа градиентов:

  • Линейные градиенты (идет вниз/вверх/влево/вправо/по диагонали)
  • Радиальные градиенты (определяемые их центром)

CSS линейные градиенты

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

Синтаксис

background: linear-gradient(direction , color-stop1 , color-stop2, ... );

Линейный градиент-сверху вниз (по умолчанию)

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

Пример

#grad {
background: linear-gradient(red, yellow);
}

Линейный градиент-слева направо

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

Пример

#grad {
background: linear-gradient(to right, red , yellow);
}

Линейный градиент-Диагональ

Можно сделать градиент по диагонали, указав как горизонтальные, так и вертикальные начальные позиции.

В следующем примере показан линейный градиент, начинающийся в левом верхнем углу (и направляется в нижний правый угол). Оно начинает красно, переходя к желтому цвету:

Пример

#grad {
background: linear-gradient(to bottom right, red, yellow);
}

Использование углов

Если требуется больший контроль над направлением градиента, можно определить угол, а не предопределенные направления (снизу, сверху, вправо, влево, вниз вправо и т.д.).

Синтаксис

background: linear-gradient(angle , color-stop1 , color-stop2 );

Угол указывается в виде угла между горизонтальной линией и линией градиента.

В следующем примере показано, как использовать углы на линейных градиентах:

Пример

#grad {
background: linear-gradient(-90deg, red, yellow);
}

Использование нескольких цветовых остановок

В следующем примере показан линейный градиент (сверху вниз) с несколькими остановками цвета:

Пример

#grad {
background: linear-gradient(red, yellow, green);
}

В следующем примере показано, как создать линейный градиент (слева направо) с цветом радуги и некоторым текстом:

Градиентный фон

Пример

#grad {
background: linear-gradient(to right, red,orange,yellow,green,blue,indigo,violet);
}

Note: Internet Explorer 9 and earlier versions do not support gradients.

"/> Просмотр демо в редакторе

Использование прозрачности

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

Чтобы добавить прозрачность, мы используем функцию RGBA () для определения ограничителей цвета. Последний параметр в функции RGBA () может быть значением от 0 до 1, и он определяет прозрачность цвета: 0 указывает на полную прозрачность, 1 указывает на полный цвет (без прозрачности).

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

Пример

#grad {
background: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1));
}

Повторение линейного градиента

Функция повторения-линейного градиента () используется для повторения линейных градиентов:

Пример

Повторяющийся линейный градиент:

#grad {
background: repeating-linear-gradient(red, yellow 10%, green 20%);
}

CSS радиальные градиенты

Радиальный градиент определяется его центром.

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

Синтаксис

background: radial-gradient(shape size at position, start-color, ..., last-color );

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

Радиальный градиент-равномерное расстояние между цветами останавливается (по умолчанию)

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

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

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 value, followed by an one or two optional stop positions (either a or a 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,