How to make gradient css

How to make gradient css

linear-gradient()

Try it

Syntax

Values

The gradient line’s angle of direction. A value of 0deg is equivalent to to top ; increasing values rotate clockwise from there.

A color-stop’s value, followed by one or two optional stop positions, (each being either a

or a along the gradient’s axis).

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.

Note: Rendering of color stops in CSS gradients follows the same rules as color stops in SVG gradients.

Note also that the first example above does not exactly render as depicted in Mozilla Firefox (particularly version 80.0b3). You’ll have to set the html height property to 100% or 100vh to render as depicted.

Description

As with any gradient, a linear gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to.

To create a linear gradient that repeats so as to fill its container, use the repeating-linear-gradient() function instead.

Because s belong to the data type, they can only be used where s can be used. For this reason, linear-gradient() won’t work on background-color and other properties that use the data type.

Composition of a linear gradient

A linear gradient is defined by an axis—the gradient line—and two or more color-stop points. Each point on the axis is a distinct color; to create a smooth gradient, the linear-gradient() function draws a series of colored lines perpendicular to the gradient line, each one matching the color of the point where it intersects the gradient line.

How to make gradient css. Смотреть фото How to make gradient css. Смотреть картинку How to make gradient css. Картинка про How to make gradient css. Фото How to make gradient css

The gradient line is defined by the center of the box containing the gradient image and by an angle. The colors of the gradient are determined by two or more points: the starting point, the ending point, and, in between, optional color-stop points.

The starting point is the location on the gradient line where the first color begins. The ending point is the point where the last color ends. Each of these two points is defined by the intersection of the gradient line with a perpendicular line passing from the box corner which is in the same quadrant. The ending point can be understood as the symmetrical point of the starting point. These somewhat complex definitions lead to an interesting effect sometimes called magic corners: the corners nearest to the starting and ending points have the same color as their respective starting or ending points.

Customizing Gradients

By adding more color-stop points on the gradient line, you can create a highly customized transition between multiple colors. A color-stop’s position can be explicitly defined by using a or a

. If you don’t specify the location of a color, it is placed halfway between the one that precedes it and the one that follows it. The following two gradients are equivalent.

By default, colors transition smoothly from the color at one color stop to the color at the subsequent color stop, with the midpoint between the colors being the half way point between the color transition. You can move this midpoint to any position between two color stops by adding an unlabelled % color hint between the two colors to indicate where the middle of the color transition should be. The following example is solid red from the start to the 10% mark and solid blue from 90% to the end. Between 10% and 90% the color transitions from red to blue, however the midpoint of the transition is at the 30% mark rather than 50% as would have happened without the 30% color hint.

If two or more color stops are at the same location, the transition will be a hard line between the first and last colors declared at that location.

Color stops should be listed in ascending order. Subsequent color stops of lower value will override the value of the previous color stop creating a hard transition. The following changes from red to yellow at the 40% mark, and then transitions from yellow to blue over 25% of the gradient

Multi-position color stop are allowed. A color can be declared as two adjacent color stops by including both positions in the CSS declaration. The following three gradients are equivalent:

By default, if there is no color with a 0% stop, the first color declared will be at that point. Similarly, the last color will continue to the 100% mark, or be at the 100% mark if no length has been declared on that last stop.

CSS Gradients

CSS gradients let you display smooth transitions between two or more specified colors.

CSS defines three types of gradients:

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

The following example shows a linear gradient that starts at the top. It starts red, transitioning to yellow:

Example

The following example shows a linear gradient that starts from the left. It starts red, transitioning to yellow:

Example

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:

Using CSS gradients

We’ll start by introducing linear gradients, then introduce features that are supported in all gradient types using linear gradients as the example, then move on to radial, conic and repeating gradients

Using linear gradients

A linear gradient creates a band of colors that progress in a straight line.

A basic linear gradient

To create the most basic type of gradient, all you need is to specify two colors. These are called color stops. You must have at least two, but you can have as many as you want.

Changing the direction

By default, linear gradients run from top to bottom. You can change their rotation by specifying a direction.

Diagonal gradients

You can even make the gradient run diagonally, from corner to corner.

Using angles

If you want more control over its direction, you can give the gradient a specific angle.

When using an angle, 0deg creates a vertical gradient running bottom to top, 90deg creates a horizontal gradient running left to right, and so on in a clockwise direction. Negative angles run in the counterclockwise direction.

How to make gradient css. Смотреть фото How to make gradient css. Смотреть картинку How to make gradient css. Картинка про How to make gradient css. Фото How to make gradient css

Declaring colors & creating effects

All CSS gradient types are a range of position-dependent colors. The colors produced by CSS gradients can vary continuously with position, producing smooth color transitions. It is also possible to create bands of solid colors, and hard transitions between two colors. The following are valid for all gradient functions:

Using more than two colors

You don’t have to limit yourself to two colors—you may use as many as you like! By default, colors are evenly spaced along the gradient.

Positioning color stops

Creating hard lines

To create a hard line between two colors, creating a stripe instead of a gradual transition, adjacent color stops can be set to the same location. In this example, the colors share a color stop at the 50% mark, halfway through the gradient:

Gradient hints

By default, the gradient transitions evenly from one color to the next. You can include a color-hint to move the midpoint of the transition value to a certain point along the gradient. In this example, we’ve moved the midpoint of the transition from the 50% mark to the 10% mark.

Creating color bands & stripes

To include a solid, non-transitioning color area within a gradient, include two positions for the color stop. Color stops can have two positions, which is equivalent to two consecutive color stops with the same color at different positions. The color will reach full saturation at the first color stop, maintain that saturation through to the second color stop, and transition to the adjacent color stop’s color through the adjacent color stop’s first position.

In the first example above, the lime goes from the 0% mark, which is implied, to the 20% mark, transitions from lime to red over the next 10% of the width of the gradient, reach solid red at the 30% mark, and staying solid red up until 45% through the gradient, where it fades to cyan, being fully cyan for 15% of the gradient, and so on.

In the second example, the second color stop for each color is at the same location as the first color stop for the adjacent color, creating a striped effect.

In both examples, the gradient is written twice: the first is the CSS Images Level 3 method of repeating the color for each stop and the second example is the CSS Images Level 4 multiple color stop method of including two color-stop-lengths in a linear-color-stop declaration.

Controlling the progression of a gradient

By default, a gradient evenly progresses between the colors of two adjacent color stops, with the midpoint between those two color stops being the midpoint color value. You can control the interpolation, or progression, between two color stops by including a color hint location. In this example, the color reaches the midpoint between lime and cyan 20% of the way through the gradient rather than 50% of the way through. The second example does not contain the hint to highlight the difference the color hint can make:

Overlaying gradients

Gradients support transparency, so you can stack multiple backgrounds to achieve some pretty fancy effects. The backgrounds are stacked from top to bottom, with the first specified being on top.

Stacked gradients

You can even stack gradients with other gradients. As long as the top gradients aren’t entirely opaque, the gradients below will still be visible.

Using radial gradients

Radial gradients are similar to linear gradients, except that they radiate out from a central point. You can dictate where that central point is. You can also make them circular or elliptical.

A basic radial gradient

As with linear gradients, all you need to create a radial gradient are two colors. By default, the center of the gradient is at the 50% 50% mark, and the gradient is elliptical matching the aspect ratio of it’s box:

Positioning radial color stops

Again like linear gradients, you can position each radial color stop with a percentage or absolute length.

Positioning the center of the gradient

You can position the center of the gradient with keyterms, percentage, or absolute lengths, length and percentage values repeating if only one is present, otherwise in the order of position from the left and position from the top.

Sizing radial gradients

Example: closest-side for ellipses

This example uses the closest-side size value, which means the size is set by the distance from the starting point (the center) to the closest side of the enclosing box.

Example: farthest-corner for ellipses

Example: closest-side for circles

Example: length or percentage for ellipses

For ellipses only, you can size the ellipse using a length or percentage. The first value represents the horizontal radius, the second the vertical radius, where you use a percentage this corresponds to the size of the box in that dimension. In the below example I have used a percentage for the horizontal radius.

Example: length for circles

Stacked radial gradients

Just like linear gradients, you can also stack radial gradients. The first specified is on top, the last on the bottom.

Using conic gradients

The conic-gradient() CSS function creates an image consisting of a gradient with color transitions rotated around a center point (rather than radiating from the center). Example conic gradients include pie charts and color wheels, but they can also be used for creating checker boards and other interesting effects.

The conic-gradient syntax is similar to the radial-gradient syntax, but the color-stops are placed around a gradient arc, the circumference of a circle, rather than on the gradient line emerging from the center of the gradient, and the color-stops are percentages or degrees: absolute lengths are not valid.

In a radial gradient, the colors transition from the center of an ellipse, outward, in all directions. With conic gradients, the colors transition as if spun around the center of a circle, starting at the top and going clockwise. Similar to radial gradients, you can position the center of the gradient. Similar to linear gradients, you can change the gradient angle.

A basic conic gradient

As with linear and radial gradients, all you need to create a conic gradient are two colors. By default, the center of the gradient is at the 50% 50% mark, with the start of the gradient facing up:

Positioning the conic center

Like radial gradients, you can position the center of the conic gradient with keyterms, percentage, or absolute lengths, with the keyword «at»

Changing the angle

By default, the different color stops you specify are spaced equidistantly around the circle. You can position the starting angle of the conic gradient using the «from» keyword at the beginning followed by an angle or a length, and you can specify different positions for the colors stops by including an angle or length after them.

Using repeating gradients

The size of the gradient line or arc that repeats is the length between the first color stop value and the last color stop length value. If the first color stop just has a color and no color stop length, the value defaults to 0. If the last color stop has just a color and no color stop length, the value defaults to 100%. If neither is declared, the gradient line is 100% meaning the linear and conic gradients will not repeat and the radial gradient will only repeat if the radius of the gradient is smaller than the length between the center of the gradient and the farthest corner. If the first color stop is declared, and the value is greater than 0, the gradient will repeat, as the size of the line or arc is the difference between the first color stop and last color stop is less than 100% or 360 degrees.

Repeating linear gradients

This example uses repeating-linear-gradient() to create a gradient that progresses repeatedly in a straight line. The colors get cycled over again as the gradient repeats. In this case the gradient line is 10px long.

Multiple repeating linear gradients

Similar to regular linear and radial gradients, you can include multiple gradients, one on top of the other. This only makes sense if the gradients are partially transparent allowing subsequent gradients to show through the transparent areas, or if you include different background-sizes, optionally with different background-position property values, for each gradient image. We are using transparency.

In this case the gradient lines are 300px, 230px, and 300px long.

Plaid gradient

To create plaid we include several overlapping gradients with transparency. In the first background declaration we listed every color stop separately. The second background property declaration using the multiple position color stop syntax:

Repeating radial gradients

This example uses repeating-radial-gradient() to create a gradient that radiates repeatedly from a central point. The colors get cycled over and over as the gradient repeats.

Несколько слов о градиентах

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

How to make gradient css. Смотреть фото How to make gradient css. Смотреть картинку How to make gradient css. Картинка про How to make gradient css. Фото How to make gradient css

Сегодня мало кто не знает, что такое градиенты и как их применять в разработке. Если верить статьям, то в 2018 году, применение ярких и насыщенных градиентов — это некий тренд.

Что такое градиент?

Давайте, для галочки, вспомним, что такое градиент.

Градие́нт (от лат. gradiens, род. падеж gradientis — шагающий, растущий) — вектор, своим направлением указывающий направление наибольшего возрастания некоторой величины <\displaystyle \varphi >\varphi, значение которой меняется от одной точки пространства к другой (скалярного поля), а по величине (модулю) равный скорости роста этой величины в этом направлении

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

Форма записи градиентов в css

Давайте коротко рассмотрим, из чего же состоит классический градиент.

Градиент может быть записан двумя способами:

background: linear-gradient(36deg, #0dd3ff, #0389ff, #1c79c0);
background-image: linear-gradient(36deg, #0dd3ff, #0389ff, #1c79c0);

Какую форму записи использовать — решать вам.

В коде, приведенном выше, мы указали три значения свойств background:

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

Написание цвета градиентов

Цвет градиента может быть записан любым доступным обозначением:

Вы также можете указывать цвета в процентном соотношении, добавив после цвета %. Например, rgb(0, 0, 0) 0%, rgb(255,255,255) 100%.

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

Градиенты с изображениями

Для записи комбинированного градиента, с картинкой в качестве фона, можно использовать и другие свойства background. Давайте рассмотрим на двух примерах:

В первом примере мы создали градиентный фон (пример 1), а во втором добавили изображение и наложили на него наш градиент (пример 2).

Градиент для текста

Иногда хочется сделать текст ссылки или заголовка более ярким, заметным и/или заменить обычный текст на какую-нибудь картинку. CSS позволяет нам это сделать, используя следующие свойства:

Аналогичные действия можно совершать, заменив градиент на ссылку с изображением.

Главное помните, что некоторые свойства поддерживаются не всеми версиями браузеров. Проверить совместимость можно на сайте Can I use

Объединение градиентов CSS в режиме Background Blend Mode

Такие функции, как linear-gradient(), radial-gradient(), и repeating-linear-gradient(), repeating-radial-gradient() и другие разновидности имеют широкую поддержку и более стандартизированный синтаксис во всех современных браузерах. Однако, свойство background также может включать в себя более одного градиента, причем каждая функция разделяется запятой. Lea Verou продемонстрировала впечатляющие модели — паттерны, которые могут быть созданы с помощью этой техники: от шахматных досок, до кирпичей, до звезд. Но теперь, когда у нас есть свойство background-blend-mode, мы можем создать новые градиенты и шаблоны. Примеры ниже.

Спектральный фон

Наложим три градиента, чтобы создать фон с почти полным спектром цветов, который можно отобразить на мониторе.
.spectrum-background <
background:
linear-gradient(red, transparent),
linear-gradient(to top left, lime, transparent),
linear-gradient(to top right, blue, transparent);
background-blend-mode: screen;
>

How to make gradient css. Смотреть фото How to make gradient css. Смотреть картинку How to make gradient css. Картинка про How to make gradient css. Фото How to make gradient css
И вот у нас уже получился разноцветный фон. Создание подобного эффекта ранее было возможно только с изображением, вес которого составлял бы десятки килобайт. Но мы только что воспроизвели этот эффект через CSS менее чем на 200 байт, не говоря уже о сохранении HTTP-запроса.

Создаем плед на css

Мы также можем создать интересные шаблоны с градиентами при помощи background-blend-mode.
.plaid-background <
background:
repeating-linear-gradient(
-45deg,
transparent 0,
transparent 25%,
dodgerblue 0,
dodgerblue 50%
),
repeating-linear-gradient(
45deg,
transparent 0,
transparent 25%,
tomato 0,
tomato 50%
),
repeating-linear-gradient(
transparent 0,
transparent 25%,
gold 0,
gold 50%
), white;
background-blend-mode: multiply;
background-size: 100px 100px;
>

В итоге вот что у нас получилось,
How to make gradient css. Смотреть фото How to make gradient css. Смотреть картинку How to make gradient css. Картинка про How to make gradient css. Фото How to make gradient css

Фон сайта с кружочками

Эффект ночного видения

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

Возьмем обычное изображение
How to make gradient css. Смотреть фото How to make gradient css. Смотреть картинку How to make gradient css. Картинка про How to make gradient css. Фото How to make gradient css
и наложим на него радиальный градиент и градиент, который мы использовали при создании пледа — repeating-linear-gradient
.night-vision-effect <
background:
url(https://wallpaperbrowse.com/media/images/soap-bubble-1958650_960_720.jpg),
radial-gradient(
rgba(0,255,0,.8),
black
),
repeating-linear-gradient(
transparent 0,
rgba(0,0,0,.2) 3px,
transparent 6px
);
background-blend-mode: overlay;
background-size: cover;
>

И вот результат.

Сайты-генераторы градиентов

Ниже я приведу подборку сайтов, позволяющих генерировать те самые градиенты, делать из них canvas, png и svg форматы и копировать код для установки в ваши проекты.

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

Всем удачи и приятного творчества. Пишите в комментариях свои любимые градиенты.

Make Beautiful Gradients

So here’s a CSS linear gradient, going from pure yellow to pure blue:

Notice that it gets kinda washed out and muddy in the middle there?

This is what Erik Kennedy has coined the “gray dead zone”. Unless you’re really careful when selecting colors for your gradients, you’ll often wind up with a desaturated midsection in your CSS gradients.

As it turns out, though, we can absolutely avoid the gray dead zone. In this blog post, we’re going to learn about why this happens, and how we can use color theory to create rich, vivid, thoroughly-alive gradients.

Have you ever wondered how the CSS linear-gradient algorithm works? How does it actually calculate the specific color value for every pixel along the spectrum?

It figures it out by taking the mathematical average for each of the 3 color channels: Red, Green, and Blue.

Click and drag to see the specific RGB breakdown for every pixel along the way:

How to use: Click and drag to reposition the indicator, or focus the indicator and use the left/right arrow keys.

In the RGB color space, we create colors by mixing three channels: red, green, and blue. Each channel has a range from 0 to 255.

If we max out all three channels — 255 / 255 / 255 — we get pure white. And if we set each channel to 0, we get black, the absence of any color.

In fact, if all 3 channels are set to the same value, the result will always be a grayscale color:

In the demo above, we start at pure yellow (255/255/0). As we move through the gradient, we start mixing in the blue (0/0/255). By the time we reach the very center, we’ve mixed out half of the yellow, and mixed in half of the blue.

In other words, all three channels converge towards their middle value, 127.5. And the resulting color is gray.

It’s a bit weird to me that the midpoint between blue and yellow is gray. By mixing two highly-saturated colors together, we wind up with a totally-desaturated color. What if there was a way to mix only the pigment, and keep the saturation consistent throughout?

There are lots of different ways to represent color. So far, we’ve been using the R/G/B mode. And, honestly, this color mode kinda sucks. 😅

Let’s talk about a different color mode: HSL.

HSL stands for Hue / Saturation / Lightness. If you’ve ever used a color picker, you’ve probably worked with this color mode. *

Here’s a live example:

Here’s what each value represents:

Personally, I find that this is a much more intuitive way to think about color.

Here’s the really magical thing: what if, instead of averaging out the RGB values in our gradients, we average out the HSL values?

Well, let’s try it:

There’s no more gray dead zone, because we’re not mixing R/G/B values anymore, we’re mixing H/S/L values.

The start color and end color share the same saturation and lightness, and so the only value that changes is the hue. As a result, we’re effectively walking through the color wheel.

Here’s another example, this time mixing colors with different saturations and lightnesses:

And here are the same colors, using typical RGB mixing:

Quite a difference, right?

Now, HSL isn’t necessarily the best color mode to use in every situation; it tends to produce gradients that can be overly bright and vivid, because it doesn’t take into account human perception.

According to the HSL color mode, both of these colors share the same “lightness”:

Not everyone sees color the same way, but most people will say that the yellow feels a lot lighter than the blue, despite them having the same «lightness» value. HSL isn’t concerned with how humans perceive colors, though; it’s modeled after the raw physics, energy and wavelengths and such.

Fortunately, there are other color modes that do take human perception into account. For example, HCL is similar to HSL, but modeled after human vision:

Which color mode is best? Well, it really depends what effect you’re after! I like to experiment with lots of different color modes, to find the best one for a particular gradient.

I have some good news and some bad news. Let’s start with the bad news.

CSS doesn’t give us any way to change the color mode used in gradient calculations. We can’t «opt in» to use HSL interpolation for a given gradient, at least not yet. CSS Images Level 4 does provide a way to specify a “color interpolation method”, but as far as I know, it isn’t widely supported in browsers.

Here’s the good news, though: we can work around this limitation if we’re a bit sneaky. 😈

Gradients in CSS don’t have to stick to only two colors. We can pass 3 colors or 10 colors or 100 colors.

First, we’ll need to manually calculate a bunch of in-between colors. We’ll do this using JavaScript, so that we can use whatever color mode we want (using a helpful library like chroma.js):

Next, we’ll take that collection of colors, and pass each value to a CSS gradient function:

(We’re using linear gradients here, but the same trick works for radial and conic gradients!)

But wait, won’t the CSS engine still use RGB interpolation to calculate the spaces between each provided color? Unless we pass hundreds of colors, enough for every single pixel, we’re still relying on RGB interpolation!

This is true, but fortunately it’s not a big deal.

When two colors are very similar to each other, it doesn’t really matter which color mode we use. You’ll wind up with approximately the same gradient. We aren’t going to get a wildly-different «average» value, no matter how you define «average».

For example, here’s a gradient that uses two very-similar colors:

The colors are so similar that there’s really no way for RGB interpolation to mess it up.

So then: our sneaky trick is to generate a bunch of midpoint colors using a custom color mode, and pass them all to our CSS gradient function. The CSS engine will use RGB interpolation, but it won’t affect the final result (at least, not by enough for it to be perceptible to humans).

Alright, now the fun part. Let’s talk about how to generate these gradients. 😄

I’ve created a tool that will help you generate lush, beautiful gradients you can use in CSS.

I’m really excited about this tool. It uses all the stuff we’ve talked about in this blog post, plus a few other nifty tricks (like using an easing curve to control the distribution of colors).

Tweak the controls until you like the result, and then copy the CSS snippet at the bottom. Right now, the tool only generates linear gradients, but you can copy/paste the set of CSS colors and use them in radial and conic gradients as well!

Oh, and one more thing: If you enjoyed this teaching style, with the interactive widgets and first-principles focus, you’ll love my CSS course, CSS for JavaScript Developers.

In my course, we take a similar approach to the entire CSS language. We learn how it works under-the-hood, so that the language stops feeling so dang surprising. We cover a bunch of common layouts and effects, but we focus on the underlying ideas, so that you can build any layout or effect with the tools you’ve learned.

If you’re interested, you can learn more here: https://css-for-js.dev/.

I was inspired to build my gradient generator after seeing these two wonderful gradient generators:

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *