Css linear gradient iphone

2.16. CSS-градиент

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()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Значение Описание
closest-side Размер градиента рассчитывается из расстояния до любой ближней стороны блока для circle или до ближних сторон по X и по У для ellipse .
farthest-side Размер рассчитывается из расстояния до дальних сторон.
closest-corner Размер рассчитывается из расстояния до ближних углов.
farthest-corner Размер рассчитывается из расстояния до дальних углов.

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

Источник

linear-gradient()

The linear-gradient() CSS function creates an image consisting of a progressive transition between two or more colors along a straight line. Its result is an object of the data type, which is a special kind of .

Syntax

Values

The position of the gradient line’s starting point. If specified, it consists of the word to and up to two keywords: one indicates the horizontal side ( left or right ), and the other the vertical side ( top or bottom ). The order of the side keywords does not matter. If unspecified, it defaults to to bottom .

The values to top , to bottom , to left , and to right are equivalent to the angles 0deg , 180deg , 270deg , and 90deg , respectively. The other values are translated into an angle.

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.

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.

Читайте также:  Apples apple id portal

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 градиент не работает на iOS

Я создал градиентный фон использование генератора CSS. Это прекрасно работает во всех основных браузерах и на Android. Однако в iOS я получаю этой.

что мне нужно добавить к этому градиенту, чтобы он работал на iOS?

Edit: поскольку этот вопрос не привлекает достаточного внимания, я хотел бы задать другой вопрос: Что мне нужно для CSS-тега для создания линейного градиента для safari / ios, когда, как в в этом случае-webkit-linear-gradient не работает? Есть ли другие теги градиента css, специально для safari?

вот код для моего фона:

3 ответов

сделайте эту проверку в iOS, но она должна работать:

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

Вариант 1

в качестве альтернативы вы можете попробовать использовать тень окна вставки. Это не точно, и у него есть ограничения, но это просто вариант:)

вариант 2

Если вы знаете высоту, либо используйте тень коробки выше или просто используйте фоновое изображение. Таким образом, вы получите поддержку кросс-браузера без беспорядка, который представляет собой сто свойств CSS с префиксом, как указано выше 🙂

В mobile safari, по крайней мере, вы не можете использовать ключевое слово transparent , вы должны использовать rgba(255,255,255,0) вместо. Доказательство: https://developer.apple.com/library/safari/documentation/internetweb/conceptual/safarivisualeffectsprogguide/Gradients/Gradient.html

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

Источник

Safari CSS Visual Effects Guide

Using Gradients

Use gradients as color fills that blend smoothly from one color to another. Use a CSS gradient anywhere that you can use an image, such as for the background of an element, an element border, or a mask. Because gradients are resolution-independent and compact, a line or two of CSS can replace hundreds of kilobytes—or even megabytes—of graphic imagery. Unlike graphic images, gradients have no inherent size, and automatically expand to fill a container.

To create a gradient, specify a starting color and an ending color, and optionally intermediate colors and a direction. Safari supports two types of CSS gradients: linear and radial. This chapter describes both types of gradients. Safari 5.1 on the desktop and Safari on iOS 5.0 use the -webkit- prefix for specifying gradients, but otherwise conform to the 17 February 2011 working draft for CSS3 gradients: http://dev.w3.org/csswg/css3-images/ .

Note: Recent drafts of the W3C proposal have simplified the syntax. This chapter describes the most recent implementation shipping in Safari. You should expect Safari’s syntax for gradients to continue to change as the W3C standard evolves. While new syntax is expected, the existing syntax—and prior syntax—should still work.

The -webkit-linear-gradient and webkit-radial-gradient properties require iOS 5.0 or later, or Safari 5.1 or later on the desktop. If you need to support earlier releases of iOS or Safari, see Prior Syntax (-webkit-gradient) .

Creating Linear Gradients

A linear gradient defines a color change along a specified line. Each point on the line has a particular color. The width of the line, perpendicular to the direction of the line, extends to the edges of the gradient’s container. You can use a linear gradient to fill any two-dimensional shape. By default, a linear gradient changes colors from top to bottom. For example:

background: -webkit-linear-gradient(aqua, white)

defines a linear gradient that starts as aqua at the top of the element and ends as white at the bottom of the element. The gradient fills the element completely, as Figure 1-1 illustrates.

Figure 1-1 Simple linear gradient

If you specify intermediate colors between the starting and ending color, the gradient blends from color to color. For example:

background: -webkit-linear-gradient(red, yellow, orange, green, blue, purple);

defines a rainbow gradient as a background. Apply this style to a div element, and the element is drawn with a rainbow background, as Figure 1-2 illustrates.

Figure 1-2 Rainbow gradient

Setting the Direction of Change

You can define a linear gradient with the color change going in any direction: from any edge or corner to its opposite edge or corner, or at any specified angle. To specify a direction from edge-to-edge or corner-to-corner, just specify the beginning edge or corner. For example:

Читайте также:  Самый лучший определитель номера для айфона

background: -webkit-linear-gradient(left, black, white);

creates a horizontal gradient going from left to right.

background: -webkit-linear-gradient(bottom right, black, white);

creates a diagonal gradient from bottom right to top left.

You can also specify color change direction by supplying an angle. Angles are given in degrees, with 0deg being straight up and proceeding counterclockwise-positive so that 90deg is horizontal left and 180deg is straight down. For example:

-webkit-linear-gradient(45deg, black, white)

creates a gradient at a 45 degree angle up and to the left.

Note: If you specify a gradient from corner to corner, the angle of the gradient changes if the parent element is resized and the shape of the element changes. Specify the direction in degrees to create a gradient with a fixed angle.

Figure 1-3 shows a diagonal gradient starting at the bottom left corner.

Figure 1-3 Diagonal gradients

Setting the Rate of Change

By default, the rate of color change for a gradient remains constant; if the gradient has three colors, the blend starts with the first color at 0% of the gradient length, reaches the second color at 50% of the gradient length, and reaches the third color at 100% of the gradient length. In other words, the first line of the gradient is the starting color, the middle line is the second color, and the last line is the third color. To modify this behavior, specify color stops. For example, the following snippet creates a gradient that changes gradually from white to cornflower blue over 90% of the gradient length and then blends quickly from to black over the remaining 10%:

-webkit-linear-gradient(left, white, cornflowerblue 90%, black)

Figure 1-4 shows such a gradient.

Figure 1-4 Setting color stop percentages

Color stops can create some striking effects. For example, specify the same color at two consecutive stops to create a band of solid color, or specify two different colors at the same percentage point to create an abrupt change in color. Figure 1-5 shows the effect these kind of color stops create.

Creating Gradient Fades

Use RGBa colors in a gradient to soften or fade colors into the background by decreasing the alpha value of the gradient. For example, Listing 1-1 creates a div element with a white background that fades to transparent. Two consecutive white color stops are used, so the div element’s background stays white for 50% of its width and then fades into the background of the element’s parent. Figure 1-6 shows the result.

Listing 1-1 Linear fade

Creating Radial Gradients

A radial gradient is a color fill that blends from one color to another with the color change proceeding radially, forming a disk clipped by the shape of the element. The disk can be a circle or an ellipse. Specify a starting and ending color, and optionally specify intermediate colors. The starting color begins at the center of the disk, and the color change proceeds outward until the ending color is reached, by default at the farthest corner of the element being filled.

By default, a radial gradient is an ellipse the height and width of the element being filled, with the center of the ellipse at the center of the element being filled. For example, the following snippet creates a radial gradient that blends from white at the center of a div element to black at the element’s outer edges, as Figure 1-7 illustrates:

Figure 1-7 Simple radial gradient

To create a circular gradient, pass in the circle parameter:

-webkit-radial-gradient(circle, white, black) .

The circle parameter parameter causes the gradient to be circular, instead of an ellipse that conforms to the shape of the element, as Figure 1-8 illustrates:

Figure 1-8 Circular gradient

Note that the shape of an element clips a circular gradient just as it does an elliptical gradient.

Moving the Center

By default, the starting point of a radial gradient is the center of the element you are filling. Change this behavior by specifying a different starting point, using horizontal or vertical offsets from the element’s top left corner. The following example creates a circular div element (a square div element with a 50% border radius), then fills it with a radial gradient whose center is offset down and to the right of the element’s upper-left corner by 30%, creating a 3D lighting effect, as Figure 1-9 illustrates:

background: -webkit-radial-gradient(30% 30%, white, black);»>

Figure 1-9 3D lighting effect

Notice that you specify the vertical and horizontal offsets are as a distance from the top and left edge of the element, and that you specify both offsets as part of a single comma-delimited parameter, separated by a space. If you specify only a single value, Safari treats it as a vertical offset.

Changing the Ending Color Location

By default, a gradient reaches its ending color at the corner of the element furthest from the specified center of the gradient. Modify this behavior by specifying closest-corner . For example:

-webkit-radial-gradient(30% 10%, closest-corner, white, black)

creates a radial gradient that begins 30% to the right and 10% below the upper-left corner of an element, and reaches its end color at the closest corner.

If you specify both the circle and the closest-corner properties, pass them in the same comma-delimited parameter, separated by a space:

-webkit-radial-gradient(30% 10%, circle closest-corner, white, black)

When the gradient ends at the closest corner, the ending color fills the remainder of the element. Figure 1-10 shows examples of identical div elements filled with radial gradients offset 30% down and to the right of the upper-left corner. Elliptical gradients are on the left of the illustration and circular gradients are on the right. Closest-corner gradient fills are above and default gradient fills are below:

Figure 1-10 Closest-corner gradient fills

Adding Color Stops

To create a multi-colored radial gradient, specify intermediate colors between the starting and ending color. For example, the following snippet creates a radial gradient that blends from white at the center to green half way out, to black at the outer edge, as Figure 1-11 illustrates:

background: -webkit-radial-gradient(white, green, black);»>

Figure 1-11 Multicolor gradient

By default, the rate of color change is constant, dividing the gradient into equal-size color blends. Modify this behavior by providing color stops that specify the distance from the gradient center to its edge for particular colors. For example, the following snippet creates a gradient that blends from white to red in just 20% of the gradient, then takes the remaining 80% to fade to black, as Figure 1-12 illustrates:

Читайте также:  What is an oak apple

Figure 1-12 Red color stop at 20%

Specify paired color stops of the same color to create bands of solid color, or specify pairs of color stops with different colors at the same percentage point to create abrupt color changes. The following snippet defines two radial gradients, one with two color stops of the same color and the other with two differently colored stops at the same percentage point. Figure 1-13 shows the result:

background: -webkit-radial-gradient(white, red 10%, red 90%, black);

background: -webkit-radial-gradient(white, yellow 20%, red 20%, black);

Figure 1-13 Color band and abrupt color change using color stops

Creating a Radial Fade

If you use RGBa colors in your color stops, you can specify both the hue and transparency of the gradient at any point. This enables you to create a gradient that blends into the background of its parent element. For example, Listing 1-2 creates a spotlight effect by fading a div element’s background from white to transparent, allowing the parent div ’s background to gradually show through. Figure 1-14 shows the result:

Listing 1-2 Radial fade

Creating Repeating Gradients

You can create a repeating pattern in a gradient in two different ways. One way is to specify a series of repeating color stops. For example, the following snippet creates linear and radial gradients with two repeating red-to-blue-to-red blend stripes:

-webkit-linear-gradient(red, blue 25%, red 50%, blue 75%, red)

-webkit-radial-gradient(red, blue 25%, red 50%, blue 75%, red)

It’s tedious to specify the color stops repeatedly when there are many repetitions, particularly if you need to calculate cumulative percentages for each color stop. To simplify the process, use the repeating gradient properties: -webkit-repeating-linear-gradient and -webkit-repeating-radial-gradient . To create a repeating gradient, specify the first set of color stops with percentages; the gradient repeats the pattern of color stops, keeping the percentages proportional, as needed to reach 100%. The syntax for repeating gradients is otherwise identical to nonrepeating gradients. The following snippet specifies color stops that fill 20% of two gradients, which creates linear and radial gradients with five repeating plum-to-powderblue-to-plum blend stripes, as Figure 1-15 illustrates.

-webkit-repeating-linear-gradient(plum, powderblue 10%, plum 20%)

-webkit-repeating-radial-gradient(plum, powderblue 10%, plum 20%)

Figure 1-15 Repeating gradient patterns

Note that the color pattern repeats from the starting color, so if the last color specified is the same as the starting color, the pattern repeats smoothly. If you specify a pattern whose last entry is different from the first entry, the color changes abruptly from the last color to the first color when the pattern repeats, instead of blending smoothly.

Using a Gradient as a Border Image

You can use a gradient anywhere you can use an image—as you would expect, this means you can use a gradient as a border image. However, the syntax is nonobvious. The border-image property uses four values to specify offsets for slicing the image into the top, bottom, and sides of the border. Since a gradient has no inherent size, a pixel or percentage offset into the image is meaningless; the only useful value is 100% .

To make tiles from a linear gradient so that the border edges have the same color everywhere the tiles meet, start and end the gradient with the same color. For example, the following snippet creates a border like the one that Figure 1-16 shows.

-webkit-border-image: -webkit-linear-gradient(red, white, red) 100% 100% 100% 100% stretch stretch;»>

Figure 1-16 Linear gradient border

Radial gradients work nicely as borders, because the outer edges of all the tiles typically match when the stretch value is used for the repeat parameter.

Here is an example of a radial gradient used as a border image:

-webkit-border-image: -webkit-radial-gradient(white,red) 100% 100% 100% 100% stretch stretch;»>

Figure 1-17 shows the result.

Figure 1-17 Radial gradient border

Prior Syntax (-webkit-gradient)

Note: Recent drafts of the W3C proposal have simplified the syntax. This chapter describes the most recent implementation shipping in Safari. You should expect Safari’s syntax for gradients to continue to change as the W3C standard evolves. While new syntax is expected, the existing syntax—and prior syntax—should still work.

The -webkit-linear-gradient and webkit-radial-gradient properties require iOS 5.0 or later, or Safari 5.1 or later on the OS X.

The -webkit-linear-gradient and -webkit-radial-gradient properties are supported in iOS 5.0 and later, and in Safari 5.1 and later on the desktop. In prior versions of Safari, both linear and radial gradients were implemented using the -webkit-gradient property. If you need to support earlier versions of iOS or Safari, use the -webkit-gradient property to create gradients. The syntax is as follows:

Specify linear gradients using the keyword linear , followed by a starting point, an ending point, a starting color with the keyword from , any color stops, and an ending color with the keyword to .

Linear gradient, vertical from top:

-webkit-gradient(linear, center top, center bottom, from(white), to(black))

Linear gradient, horizontal from left:

-webkit-gradient(linear, center left, center right, from(white), to(black))

Linear gradient, diagonal from upper left:

-webkit-gradient(linear, upper left, lower right, from(white), to(black))

Linear gradient, rainbow:

-webkit-gradient(linear, center left, center right, from(yellow), color-stop(20%, orange), color-stop(40%, red), color-stop(60%, green), color-stop(80%, blue), to(purple))

Specify radial gradients using the keyword radial , followed by a starting point, a starting radius, an ending point, an ending radius, a starting color, any color stops, and an ending color.

Radial gradient, centered:

-webkit-gradient(radial, center center, 0px, center center, 100%, from(white), to(black))

Radial gradient, offset:

-webkit-gradient(radial, 20% 20%, 0px, 20% 20%, 60px, from(white), to(black))

Radial gradient, rainbow:

-webkit-gradient(radial, center center, 0px, center center, 100%, from(yellow), color-stop(20%, orange), color-stop(40%, red), color-stop(60%, green), color-stop(80%, blue), to(purple))

The beginning radius specifies the size of the disk at the center of the gradient. The ending radius specifies the size of the disk at the end of the gradient. The gradient is circular if the beginning and ending center points are the same, elliptical otherwise. The gradient is clipped by the shape of the containing element if the ending radius specifies a larger disk than the element can contain.

Copyright © 2016 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2016-10-27

Источник

Оцените статью