Safari bug with gradients that fade to "transparent"

Say you have a gradient in CSS that goes from red to transparent. Easy, right? Like this:

Code language: CSS

There is a pretty big gotcha here, though. In Chrome (also Android), Firefox, and Edge, you’d be all good.

A side by side comparison of Chrome, Edge, and Firefox, all displaying the same test page containing two rectangles, which have a gradient background that starts red at the top and fades to transparent at the bottom of each rectangle.

But in Safari (also iOS), you’d not be good.

The same test page as before, viewed in both the iOS simulator version of Safari, and the macOS version of Safari. The two rectangles, each with a gradient background colour are different this time. The red in the rectangle on the left fades from red to black, as it fades to transparent, which appears to be a bug. The rectangle on the right fades to transparent while still maintaining the red colour, as expected.

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.

css linear gradient transparent safari

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.

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

css linear gradient transparent safari

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.

css linear gradient transparent safari

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.

css linear gradient transparent safari

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

css linear gradient transparent safari

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:

<div style="background: -webkit-radial-gradient(white,black);">

css linear gradient transparent safari

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:

css linear gradient transparent safari

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:

<div style="width: 200px; height: 200px; border-radius: 50%;

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

css linear gradient transparent safari

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:

css linear gradient transparent safari

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:

<div style="width: 200px; height: 200px; border-radius: 100px;

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

css linear gradient transparent safari

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:

<div style="background: -webkit-radial-gradient(white, red 20%, black);">

css linear gradient transparent safari

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

css linear gradient transparent safari

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

css linear gradient transparent safari

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

css linear gradient transparent safari

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.

<div style="border-width: 50px; border-style: solid;

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

css linear gradient transparent safari

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.

css linear gradient transparent safari

Prior Syntax (-webkit-gradient)

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

Sending feedback…

We’re sorry, an error has occurred..

Please try submitting your feedback later.

Thank you for providing feedback!

Your input helps improve our developer documentation.

How helpful is this document?

How can we improve this document.

* Required information

To submit a product bug or enhancement request, please visit the Bug Reporter page.

Please read Apple's Unsolicited Idea Submission Policy before you send us your feedback.

  • CSS Tutorial
  • CSS Exercises
  • CSS Interview Questions
  • CSS Selectors
  • CSS Properties
  • CSS Functions
  • CSS Examples
  • CSS Cheat Sheet
  • CSS Templates
  • CSS Frameworks
  • CSS Formatter

How to Set Transparency with Linear Gradient in CSS ?

In web design, colors, and gradients play a vital role in crafting visually appealing websites. Incorporating transparency into specific elements can further enhance their visual impact. We’ll explore three methods for achieving transparency with linear gradients in CSS including, background image, linear gradients with RGBA colors , and HSLA colors .

These are the following approaches to set Transparency with Linear Gradient in CSS:

Table of Content

  • Background-image
  • Linear Gradient with RGBA Colors
  • HSLA Colors

Using background-image

In this approach, by adjusting gradient colors using the background-image property , we can determine how clear or opaque the image appears. This method adds attractiveness to our web designs. With the help of this method, we can set transparency to the images.

Example: Illustration of transparency Using background image property in CSS.

Using RGBA Colors

In this approach, we will use the rgba() function , this function lets us define colors using the red, green, and blue (RGB) color model, along with an alpha channel to control transparency. The alpha value, ranging from 0 (fully transparent) to 1 (fully opaque), determines how transparent each color stop is along the gradient.

Example: Illustration of transparency Using linear gradient with RGBA colors in CSS.

move2p1

Using HSLA Colors

In this approach, first create a centered box with a linear gradient background using HSLA colors , which allows for transparency. The gradient transitions from red (hue 0) to blue (hue 240) with 50% saturation and lightness, while the alpha value (0.5) controls the transparency level.

Example : Illustration of transparency with Linear Gradient in CSS Using HSLA Colors in CSS.

move2p2

Please Login to comment...

Similar reads.

  • Web Technologies
  • CSS-Questions
  • How to Watch NFL Games Live Streams Free
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Using CSS gradients

CSS gradients are represented by the <gradient> data type, a special type of <image> made of a progressive transition between two or more colors. You can choose between three types of gradients: linear (created with the linear-gradient() function), radial (created with the radial-gradient() function), and conic (created with the conic-gradient() function). You can also create repeating gradients with the repeating-linear-gradient() , repeating-radial-gradient() , and repeating-conic-gradient() functions.

Gradients can be used anywhere you would use an <image> , such as in backgrounds. Because gradients are dynamically generated, they can negate the need for the raster image files that traditionally were used to achieve similar effects. In addition, because gradients are generated by the browser, they look better than raster images when zoomed in, and can be resized on the fly.

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.

Four boxes listing angle and showing associated gradient from red to white. 0deg starts at the bottom and goes up. 90deg starts at left and goes right. 180deg starts at the top and goes down. -90deg starts at right and goes left.

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

You don't have to leave your color stops at their default positions. To fine-tune their locations, you can give each one zero, one, or two percentage or, for radial and linear gradients, absolute length values. If you specify the location as a percentage, 0% represents the starting point, while 100% represents the ending point; however, you can use values outside that range if necessary to get the effect you want. If you leave a location unspecified, the position of that particular color stop will be automatically calculated for you, with the first color stop being at 0% and the last color stop being at 100% , and any other color stops being half way between their adjacent 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.

Blending gradients

In addition to transparency, stacking multiple semi-transparent gradients and stacking gradients over raster background images, gradients can be used with other CSS effects. In this example, the four <div> elements have the same two fully-opaque gradients as background images. We apply different background-blend-mode CSS property values to the last three that blend the two background images creating different effects.

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 its 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

Unlike linear gradients, you can specify the size of radial gradients. Possible values include closest-corner , closest-side , farthest-corner , and farthest-side , with farthest-corner being the default. Circles can also be sized with a length, and ellipses a length or percentage.

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

This example is similar to the previous one, except that its size is specified as farthest-corner , which sets the size of the gradient by the distance from the starting point to the farthest corner of the enclosing box from the starting point.

Example: closest-side for circles

This example uses closest-side , which makes the circle's radius to be the distance between the center of the gradient and the closest side. In this case the radius is the distance between the center and the bottom edge, because the gradient is placed 25% from the left and 25% from the bottom, and the div element's height is smaller than the width.

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

For circles the size may be given as a <length> , which is the size of the circle.

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 linear-gradient() , radial-gradient() , and conic-gradient() functions don't support automatically repeated color stops. However, the repeating-linear-gradient() , repeating-radial-gradient() , and repeating-conic-gradient() functions are available to offer this functionality.

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.

Multiple repeating radial gradients

Repeating conic gradients.

This example uses repeating-conic-gradient() to create a gradient that rotates repeatedly around a center point. In this case, the declared color stops are repeated four times.

Multiple repeating conic gradients

Just like linear and radial repeating gradients, you can stack multiple conic gradients on top of each other, creating interesting effects by using different at <position> values so the conic gradients don't overlap at their centers and different from <angle> values so the repeating effects don't line up. This example overlaps three semi-transparent repeating radial gradients that each repeat their color schemes four times. To make overlapping gradients visible, you need to ensure either that the colors of the gradients on the top of the stack are partially transparent or use the background-blend-mode CSS property.

  • Gradient functions: linear-gradient() , radial-gradient() , conic-gradient() , repeating-linear-gradient() , repeating-radial-gradient() , repeating-conic-gradient()
  • Gradient-related CSS data types: <gradient> , <image>
  • Gradient-related CSS properties: background , background-image
  • CSS Gradients Patterns Gallery, by Lea Verou
  • CSS Gradients Library, by Estelle Weyl
  • Gradient CSS Generator
  • Advanced CSS Gradient Generator

CSS Gradient Generator

Made with ❤ by Stefano Merlo © 2016-2024 • Terms & Privacy

CSS Linear Gradients

CSS3 Gradients

Jan 14, 2011

by Simon Fraser

Introduction

WebKit paved the way for gradients in CSS by adding support for -webkit-gradient back in early 2008 , and they’ve become widely used since their introduction.

Over the past several months, the CSS Working Group has had extended discussions about making the gradient syntax easier to use, and recently Tab Atkins included a proposal in the latest draft of the Image Values and Replaced Content module . WebKit and Mozilla have now implemented this proposal so that web authors can experiment with it, and provide feedback to the Working Group. Note that the proposal is still an editor’s draft, which means that it’s still possible, and even likely to change due to user feedback.

The main goal of the new syntax is simplicity; it’s now really easy to code up common gradients, as you’ll see in the examples below. A secondary goal was to specify something where implementations were compatible across browsers.

If you’re not already running one, go and grab a recent nightly build so that you can see the examples in this post.

Here are some simple examples (note that all these examples are resizable, so you can see how resizing the box affects the gradients):

Don’t forget that gradients are a type of generated image, not a property. This means that you can use them anywhere you’d use a url(image.png) .

The New Gradient Syntax

The new syntax has four gradient functions:

  • linear-gradient()
  • radial-gradient()
  • repeating-linear-gradient()
  • repeating-radial-gradient()

The names are pretty self-explanatory, but I’ll say more about repeating gradients later. One nice thing is that the syntax for the repeating and non-repeating variants is identical.

Because this specification is still in draft form, we’ve prefixed these gradient functions with -webkit- prefix. Later when the specification is out of the draft phase you’ll be able to use them without the prefix.

Linear Gradients

Since filling the element’s box is the most common use for gradients, this is the standard behavior for linear gradients . All that you have to think about is what direction you want the gradient to run in.

There are two ways to specify this. First, you can specify the side or corner where you want the gradient to start:

You can even omit the first argument, and it will default to top , giving a vertical gradient.

In the second form, you can specify the angle of the gradient axis:

Angles run counter-clockwise, and 0deg is to the right. Note how in all these cases, the gradient is just big enough to fill the box.

Radial Gradients

Radial gradients are a little more complex, because there are more options about how to fill the box. In its simplest form, the gradient is centered in the box, and is large enough to fill it to the corners:

This is equivalent to -webkit-radial-gradient(center, ellipse cover, white, black) . That optional first argument, center , can also be a point (just like background-position ), which allows you to put the origin somewhere else:

The argument after the position specifies the shape and size of the gradient, in one of two ways. The first uses some keyword for the shape ( circle , ellipse ) and size ( closest-side , closest-corner , farthest-side , farthest-corner , contain , cover ) which are self-describing. For example:

If you want to, you can specify the ending radius of the gradient explicitly, and separately for the horizontal and vertical axes:

Color Stops

It’s very easy to specify color stops with the new gradients; in the simplest case, you can just supply a list of colors:

This results in the colors being spread out evenly over the gradient. If you like, you can position specific stops, and let the browser distribute the rest between those:

Those lengths are along the gradient axis, which may be diagonal; percentages are relative to that diagonal length.

Color stops at the same position result in sharp color changes:

Repeating Gradients

The repeating forms, repeating-linear-gradient() , and repeating-radial-gradient() , have exactly the same syntax as the simple forms, but fill in the entire gradient by repeating the stops:

The stops are repeated by just aligning them end-to-end, which often results in a sharp boundary. You can avoid this by repeating the last color:

Changes from -webkit-gradient

You should be able to recreate most of the gradients you made with -webkit-gradient with this new syntax, but there are some changes to be aware of.

First, -webkit-gradient uses a two-point syntax that lets you explicitly state where a linear gradient starts and ends. linear-gradient does away with this in favor of convenient box-filling behavior. If you really want the gradient to stop before the edges of the box, you can do so via color stop placement.

Similarly, radial-gradient no longer allows you to specify different start and end points for radial gradients, so the new radial gradients are always concentric. You can, however, produce elliptical gradients with the new syntax, which was not possible with -webkit-gradient .

So is -webkit-gradient going away? Certainly not! We’ll maintain support for -webkit-gradient for the foreseeable future for all the existing content out there that uses it.

Please Give Feedback

To reiterate, we’ve implemented support for these new gradients so that you, as web developers and authors, can give feedback. The correct forum for discussion of the gradient syntax and behavior is the www-style mailing list . If you find a bug in the implementation, please file a bug at bugs.webkit.org.

CSS Gradients

Avatar of Chris Coyier

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

Just as you can declare the background of an element to be a solid color in CSS, you can also declare that background to be a gradient. Using gradients declared in CSS, rather using an actual image file, is better for control and performance.

Gradients are typically one color that fades into another, but in CSS you can control every aspect of how that happens, from the direction to the colors (as many as you want) to where those color changes happen. Let’s go through it all.

Gradients are background-image

While declaring the a solid color uses background-color property in CSS, gradients use background-image . This comes in useful in a few ways which we’ll get into later. The shorthand background property will know what you mean if you declare one or the other.

Linear Gradient

Perhaps the most common and useful type of gradient is the linear-gradient() . The gradients “axis” can go from left-to-right, top-to-bottom, or at any angle you chose.

Not declaring an angle will assume top-to-bottom:

Those comma-separated colors can type of color you normally use: Hex, named colors , rgba , hsla , etc.

To make it left-to-right, you pass an additional parameter at the beginning of the linear-gradient() function starting with the word “to”, indicating the direction, like “to right”:

This “to” syntax works for corners as well. For instance, if you wanted the axis of the gradient to start at the bottom left corner and go to the top right corner, you could say “to top right”:

If that box was square, the angle of that gradient would have been 45°, but since it’s not, it isn’t. If you wanted to make sure it was 45°, you could declare that:

You aren’t limited to just two colors either. In fact you can have as many comma-separated colors as you want. Here’s four:

You can also declare where you want any particular color to “start”. Those are called “color-stops”. Say you wanted yellow to take up the majority of the space, but red only a little bit in the beginning, you could make the yellow color-stop pretty early:

We tend to think of gradients as fading colors, but if you have two color stops that are the same, you can make a solid color instantly change to another solid color. This can be useful for declaring a full-height background that simulates columns.

Browser Support / Prefixes

So far we’ve only looked at the new syntax, but CSS gradients have been around for quite a while. Browser support is good. Where it gets tricky is syntax and prefixing. There are three different syntaxes that browsers have supported. This isn’t what they are officially called, but you can think of it like:

  • Old: original WebKit-only way, with stuff like from() and color-stop()
  • Tweener: old angle system, e.g. “left”
  • New: new angle system, e.g. “to right”

And then prefixing as well.

Let’s try a chart:

There is some overlap in there. For instance when a browser supports the New syntax they probably also support the older syntaxes as well, including the prefix. Best practice is: if it supports New, use New.

So if you wanted to absolute deepest possible browser support, a linear gradient might look like this:

That’s an awful lot of code there. Doing it by hand would be error-prone and a lot of work. Autoprefixer does a good job with it, allowing you to trim that amount of code back as you decide what browsers to support.

The Compass mixin can do SVG data URI’s for IE 9 if that’s important to you.

To complicate things just a little more , the way degrees work in the OLD vs NEW syntax is a bit different. The OLD (and TWEENER – usually prefixed) way defines 0deg and left-to-right and proceeds counter-clockwise , while the NEW (usually unprefixed) way defines 0deg as bottom-to-top and proceeds clockwise .

OLD (or TWEENER) = (450 – new) % 360

or even simpler:

NEW = 90 – OLD OLD = 90 – NEW

OLD linear-gradient(135deg, red, blue) NEW linear-gradient(315deg, red, blue)

Internet Explorer (IE) 6-9, while they don’t support the CSS gradient syntax, do offer a programmatic way to do background gradients

There are some considerations here on deciding to use this or not:

  • filter is generally considered a bad practice for performance,
  • background-image overrides filter, so if you need to use that for a fallback, filters are out. If a solid color is an acceptable fallback ( background-color ), filter is a possibility

Even though filters only work with hex values, you can still get alpha transparency by prefacing the hex value with the amount of transparency from 00 (0%) to FF (100%). Example:

rgba(92,47,90,1) == #FF5C2F5A rgba(92,47,90,0) == #005C2F5A

Radial Gradients

Radial gradient differ from linear in that they start at a single point and emanate outwards. Gradients are often used to simulate a lighting, which as we know isn’t always straight, so they can be useful to make a gradient seem even more natural.

The default is for the first color to start in the ( center center ) of the element and fade to the end color toward the edge of the element. The fade happens at an equal rate no matter which direction.

You can see how that gradient makes an elliptical shape, since the element is not a square. That is the default ( ellipse , as the first parameter), but if we say we want a circle we can force it to be so:

Notice the gradient is circular, but only fades all the way to the ending color along the farthest edge. If we needed that circle to be entirely within the element, we could ensure that by specifying we want the fade to end by the “closest-side” as a space-separated value from the shape, like:

The possible values there are: closest-corner , closest-side , farthest-corner , farthest-side . You can think of it like: “I want this radial gradient to fade from the center point to the __________, and everywhere else fills in to accommodate that.”

A radial gradient doesn’t have to start at the default center either, you can specify a certain point by using “at ______” as part of the first parameter, like:

I’ll make it more obvious here by making the example a square and adjusting a color-stop:

Browser support for radial gradients is largely the same as linear-gradient() , except a very old version of Opera, right when they started supporting gradients, only did linear and not radial.

But similar to linear, radial-gradient() has gone through some syntax changes. There is, again: “Old”, “Tweener”, and “New”.

The hallmarks being:

  • Old: Prefixed with -webkit- , stuff like from() and color-stop()
  • Tweener: First param was location of center. That will completely break now in browsers that support new syntax unprefixed, so make sure any tweener syntax is prefixed.
  • New: Verbose first param, like “circle closest-corner at top right”

Again, I’d let Autoprefixer handle this. You write in the newest syntax, it does fallbacks. Radial gradients are more mind-bending than linear, so I’d recommend attempting to just get comfortable with the newest syntax and going with that (and if necessary, forget what you know about older syntaxes).

Conic Gradients

A conic gradient is similar to a radial gradient. Both are circular and use the center of the element as the source point for color stops. However, where the color stops of a radial gradient emerge from the center of the circle, a conic gradient places them around the circle.

css linear gradient transparent safari

They’re called “conic” because they tend to look like the shape of a cone that is being viewed from above. Well, at least when there is a distinct angle provided and the contrast between the color values is great enough to tell a difference.

The conic gradient syntax is easier to understand in plain English:

Make a conic-gradient that is located at [some point] that starts with [one color] at some angle and ends with [another color] at [some angle]

At it’s most basic level, it looks like this:

…where it is assumed that the location of the gradient starts at the very center of the element ( 50% 50% ) and is evenly distributed between white and black color values.

We could have written this in several other ways, all of which are valid:

If we do not specify an angle for the colors, then it is assumed that the gradient is evenly divided between the colors, starting at 0deg and ending at 360deg . That kind of creates a hard stop where the colors bump right up to one another at 0deg and 360deg . If our starting color would begin somewhere else on the circle, say one quarter of the way at 90deg , then that creates a smoother gradient and we start to get that cool cone-looking perspective.

css linear gradient transparent safari

We can have fun with conic gradients. For exmaple, we can use it to create the same sort of pattern you might see in a color picker or the infamous Mac spinning beach ball indicator:

css linear gradient transparent safari

Or, let’s try a simple pie chart by adding hard stops between three color values:

css linear gradient transparent safari

Unfortunately, conic-gradient has no browser support at the time of this writing. It’s currently part of the CSS Image and Replaced Content Module Level 4 specification, which is in working draft. In the meantime, Lea Verou (who has contributed to the spec) provides a polyfill that makes them possible.

This browser support data is from Caniuse , which has more detail. A number indicates that browser supports the feature at that version and up.

Mobile / Tablet

Repeating gradients.

With ever-so-slightly less browser support are repeating gradients. They come in both linear and radial varieties.

There is a trick, with non-repeating gradients, to create the gradient in such a way that if it was a little tiny rectangle, it would line up with other little tiny rectangle versions of itself to create a repeating pattern. So essentially create that gradient and set the background-size to make that little tiny rectangle. That made it easy to make stripes, which you could then rotate or whatever.

With repeating-linear-gradient(), you don’t have to resort to that trickery. The size of the gradient is determined by the final color stop . If that’s at 20px, the size of the gradient (which then repeats) is a 20px by 20px square.

Same with radial:

Improper Fallback Loading

As we’ve covered, some really old browsers don’t support any CSS gradient syntax at all. If you need a fallback that is still a gradient, an image (.jpg / .png) could do the trick. The scary part with that is that some slightly-less-old browsers, that were just starting to support CSS gradients, would load the fallback image. As in, make the HTTP request for the image even though it would render the CSS gradient.

Firefox 3.5.8 did this ( see screenshot ), as well as Chrome 5- and Safari 5.0.1. See:

css linear gradient transparent safari

The good news is this isn’t really any issue anymore. The only offending browsers were Chrome and Safari and Chrome hasn’t done it since 6 and Safari hasn’t done it as of 5.1, going on three years ago.

Additional Resources

  • Snag a block of the CSS covering all prefixes/syntaxes from CSS3 Please!
  • Can I Use on gradients
  • Mozilla docs for linear gradients , repeating liner gradient , radial gradient , and repeating linear gradient .
  • Gradients Gallery (you can do some crazy patterns with gradients)

FYI: Different syntax for different rending engines, “Rendering” is spelled wrong.

Great post! I really wish there were more browsers and users using CSS3.

Yes. It is definitely worth doing now. With server side scripting and a little JavaScript the possibility increases exponentially with CSS3.

Good to know.

Jeffrey Way did a great screencast using these not long ago here http://bit.ly/9zFMQR

Thanks for posting that link. The given information was really useful to me, same counts for the article here itself. I learned a lot

Great article Chris! Would definitely will give them a go!

Can’t we report (or ask?) Mozilla and Webkit to not request the fallback image? Something like a bug/feature request?

Shorter hand for Firefox if you don’t to get to fancy.

Where you can replace top with bottom, left, or right.

Great article! Webkit have a best syntax.

Nice writeup however the demo for the 180deg example is still showing 90deg in Safari 4.0.4. Also, if we don’t invite IE (trident) to this party because there are no performance gains then the same can be said for Safari/Webkit as it too loads the image. Furthermore, and I haven’t tested this yet, would using a conditional comment to target IE with its filter utilizing the !important override force the Trident engine to use the gradient instead of the image?

The problem with Trident is twofold:

• It loads the fallback image anyway

• If a fallback image is declared it uses that instead of the gradient filter

So yes, if you could figure a way to get it to at least use the gradient filter instead of the image, there would be an advantage (programmatic declaration of color) to using it. But as written in this article, there isn’t.

We can target IE (may be conditional comments or underscore hack) and set background to “none” and declare the filter. A bit more work but it means not loading the image which worth it.

Sorry! I didn’t see your last paragraph.

There is actually a proprietary IE filter to get gradients working in IE 5.5+. You just get a start and stop value though, not the fine grained control we have in webkit and mozilla

aaaaanndd i’m assuming that’s what you meant with “filter”.

I like the fallback image solution though, seems the most logical

Like Sean mentioned, there is a small typo in the demo code. It’s the 180-degree code that is wrong though. Webkit-browsers will show 90-degree gradient in both examples with the current code.

I believe the it should be:

background-image: -webkit-gradient(linear, 0% 0%, 100% 0%, from(#1a82f7), to(#2F2727)) !important;

or, in this case, easier to understand:

background-image: -webkit-gradient(linear, left top, right top, from(#1a82f7), to(#2F2727)) !important;

Thanks for a interesting article!

Thanks I fixed that… it was just me messing with it changing stuff around as I was learning how to use it.

I’m gonna leave in the keywords version you suggested so there are examples of both ways.

Really useful to know and definitely worth implementing now. My problem with progressive enhancement to date has been that it’s only really practical for personal sites and blogs. Try explaining to a client that the beautiful gradients that he/she sees in the mock up will not actually be visible to a large proportion of the sites visitors. Now everybody sees the intended design without resorting to a conditional stylesheet.

CSS gradients are cool and sexy, but I’m not still convinced. If they weren’t declared via vendor specific syntax and their syntax was standarized, I would do the whole enhancement magic (like I do with rgba() and text-shadow). But now for me their code is too messy. Though the whole idea is just awesome.

I could not agree more. It’s weird how all the semantic, clean code aficionados are using these browser specific “css hacks”.

While I think it’s cool to stay progressive and try new things, it’s somewhat contradictory at the same time.

As of Safari 5 and Chrome 10 the syntax is standardised, and since users of these browsers are prompted heavily to update (or in Chrome’s case, updated automatically) it could be argued that we don’t need to provide the older Webkit syntax, just rely on the image fallback for the tiny minority that this would affect.

While I think this is awesome, I am getting a little tired of the fact that all of these things need 3 lines in the stylesheet to get them to work. This vendor specific syntax is annoying. And then to have to work around for IE garbage? Bah!

I’m with Mike above….when you have a client that uses an older browser and either can’t or won’t upgrade, you trying telling them that this looks awesome for others, but just ok for you.

Or, hey Mr. client, this looks great on the browser you are using, but for a lot of your visitors, some things will be missing or will look different.

Clients don’t want to hear that. They want it to be the same across the board. Progressive enhancement doesn’t mean a whole lot to them. To make it worse, the company I work for monitors what browsers our client’s visitors are using….and IE6 is STILL at about 25-30%.

I don’t think it’s useful. A serious web designer would use sprites anyway, so requests aren’t an issue here (if you have 8 gradients on your page, you’re probably not going to save 8 files if you have any idea what you’re doing) …

Not working on IE is an issue. Not working properly in webkit-based browsers (still making the request) is an issue.

I’ll stick to sprites. And most of my gradients have a lot of effects that I don’t think css can (for now) reproduce easily.

Sorry that I have to correct you Chris, but Firefox 3.6 does support radial gradients.

The syntax is fairly simple, instead of using -moz-linear-gradient you simply use -moz-radial-gradient.

Check out this article with more information: CSS Gradients in Firefox 3.6 You can also have a look at my Beautiful Photoshop-like Buttons with CSS3 Tutorial , which features radial gradients in Firefox.

Nice summary of CSS Gradients in any case, thanks!

Mozilla does support radial gradients, it’s just a different property: -moz-radial-gradient.

Check out the reference page on the Mozilla Developer’s Center

I’ll support CSS gradients when I only need one syntax, and no separate browser-declarations.

Currently you hint in the direction of damn ugly rectangle boxes with a gradient

as soon as the design requires more details this will become tricky i know that css3 will also have shadow’s and rounded corners and all, but we are still a long way from all these features working great together (with each other and with fallback images / colors)

so my oppinion would be “wait” since my boss will not agree with a site that does not look like the design (yes, to the pixel, and yes, in all major browsers including my worst enemy IE6).

I’m finding it pretty amazing how many people are against the idea of progressive enhancement, citing angry bosses and clients.

But remember…

In thise case, this isn’t “how it looks” progressive enhancement, this is “how it works” progressive enhancement. Because we can use fallbacks, the look will be the same here.

It’s little details like this that make modern web design so much fun. Being able to accomplish these things outside of photo shop will completely change how sites are designed>

Chris, I gave gradients a sincere try. Tried and tried, with all my might. I found that, in many cases, specifying for multiple browsers didn’t play nice with each other.

That is to say, specifying for both mozilla and webkit blew off one or the other. And throwing opera into the fray blew them ALL off. And throwing in the proposed W3 spec …well… nada.

I tried the specs in all orders (one first, the other first, etc.) I tried with ONE background statement, then with one each. No luck. So, I gave up and retreated to an image.

I’m a gradient fiend. I’d LOVE to use them via spec. Mebbe I’m doing something terribly wrong. But no luck yet.

Since CSS 3 support is still not that good, I would suggest different approach – using SVG for backgrounds with little Javascript (to support all mayor browsers).

Take a look at this article at AListApart.com: http://www.alistapart.com/articles/using-svg-for-flexible-scalable-and-fun-backgrounds-part-i/ .

Nice idea! I wouldn’t thought of that, beacuse I’m not used to working with svg. But I’ll give this approach a chance.

So, the question that remains is:

Why bother with fallbacks anyways?

If certain browsers do not support all aspects of CSS2 and are not beginning to support CSS3, then why should we cater to their users?

“But then things won’t look the same!”

I say, so what?

As designers and developers, I feel it is high time we abandoned trying to make everything look the same in every browser. As long as standards compliance and graceful degradation are taken into account, this should not be a problem. If certain elements do not display on certain browsers then those users do not get as rich of a user experience as others. As long as the site still works correctly, this does not matter.

Bravo…NOT. Why should you cater to their users? Because they’re the ones the website is for!

I love Progressive Enhancement (not Graceful Degredation) and really want/try to use CSS3 as much as possible but I will never make (for example) an IE7 user suffer a worse experience than a Chrome user for the sake of being cutting edge.

If one of my designers has created a great design then as far as I’m concerned as many people as possible deserve to have the opportunity to experience it.

And quite often the ‘gracefully degraded’ version looks shocking – take the rounded corners, gradient and shadow off a button and all you get is a box.

So now that little rant is over, thanks very much Chris! A very informative post!

I stand somewhere in the middle. Graceful degradation should be considered professionally. One should look at their target market/user base/budget and evaluate how much time should be spent making improvements for older browsers.

@Matt – believe me, you will hear about it from clients if you build a site that looks the way it’s supposed to in your browser and not theirs.

@Jonathan – I wouldn’t go so far as to say a use “suffers” from lack of design. I do agree sites should still be semi-attractive in older browsers, however, it’s perfectly acceptable with a limited budget to tell users with older browsers that if they upgrade they will be able to enjoy the “full” experience.

Good post Chris.

Great article Chris! I’m going to have to give this a go.

I’m sure most here have seen modernizr which detects what browsers support which html5 and css3 properties. This solves the problem of the fallback image, but introduces a 3.9 kb js file with the http request and client-side processing. I’m curious how others here feel about modernizr and if it is worth the request, size, and processing.

One of the things we want for modernizr 2.0 is a build system so you can only include the tests you want.

Until then i think it’s totally fine to use the detection technique that we use internally on your own.

And then again, 3.9k aint too huge. :)

Very exciting to hear about version 2.0! 3.9k is tiny IMO and I have been using it on all of my new sites. Was trying to find out what others thought that have used it or thought about using it.

Most likely if you are using CSS3 gradients then you are using other css3 features like border-radius, box-shadow, etc. which I would think more than justifies the js file. i am not an optimization expert yet, though.

I need to get off my ass and start using modernizr… I like everything about it.

When it comes to using some of these cooler CSS3 technologies in their early stages the other question you may want to ask is how well and fast does the browser render the CSS3.

If the CSS3 short cut takes longer than the actual image retrieval then we might as well grab the image.

As for the browser specific declarations something like http://lesscss.org/ would be ideal.

great thank you, I will definately start using CS3, does CSS3 have cross browser issues,

Found a nice interactive gradient generator here: http://gradients.glrzad.com/

http://westciv.com/tools/gradients/index.html

I really benefited from the list. Thanks for your sharing!

I recently used gradients for a site because of the advantage it creates visually since the gradient can stretch to match the height on say a background. Here’s the site:

http://www.bronzetouchwf.com/

Compare a short page to a long one or use control+mousewheel (works in Chrome on Windows) to zoom out (Document > Zoom to fix that).

It’s subtle but nice…compare to IE or another browser without gradients and you can see the difference.

Already using it. Spread the word!

I second the already using it

Chris good stuff as always thanks so much

I can get pretty lazy when it comes to having to load up PS even to create a simple image. CSS gradients are so much easier and I’m fine backing that up with a solid color for folks that can see the gradient.

Also, I wrote a little utility to display various web stats and I hate seeing image resources top the list of most http requests. I’m going through now and trimming image resources where I can. This certainly helps do that.

Just an odd note, but does the footer of this site look off in IE7 to anyone else?

nm….it is when you bring the window size in. Footer doesn’t move.

I just started to use the css gradients last month, after I saw a few Nettut articles about them.

So far, I’ve only used them for drop shadows on divs to add a bit of depth for people with Firefox, Chrome and Safari. I stay away from using them for elements that depend on them, though.

The question I ask myself: “Would the art suffer without it?” If the answer is ‘Yes,’ I use older, more reliable methods at the cost of page load speed.

Nice! Been holding off using CSS gradients with a fallback as most browsers I’d tested in downloaded the image anyway.

It’s only one browser and it’s only one http request, but it doesn’t take a lot of effort & will give performance increases

Very nice article. Definitely going to try this out.

i use right now js gradients, it works in all browsers with the same sintax, and is easy to me to make all lighter to load, using svg is agreat deal too, but don’t work on ie without a adobe plugin

Another way to look at them is that if you use subtle gradients in your site, the fallback can be no gradient at all, just a solid color. So the site won’t look good in IE8 and prior, FF3.5 and prior,Opera 9 and prior,etc. Any non-CSS3 (even partial) browser that doesn’t support the gradient rule will see a solid color. But very soon, IE9 will be out, and within perhaps a year and a half, this subtle gradient fallback of simply a solid color might be acceptable.

Great article chris. I’m going to work some css3 gradients into my next project

Great article! I spent much time on this a little while ago, wish I found your article earlier – it would have save me a lot of time.

For those who don’t want to spend to much time building their CSS gradients (like me), I created a little tool:

http://www.display-inline.fr/projects/css-gradient/

There’s also support for Opera gradients, using SVG background.

Hey Chris, nice write-up!

I’ll just add a new twist to it: What about embedding your gradient as data-URI right into your background-property? That would also save you bandwidth and works in all modern browsers (apart from…, IE of course).

In addition you could then apply IE’s filter, as IE won’t get the message with that “strange” background-property.

PS: Yes, IE knows the proprietary data-URI-equivalent of MHTML, but that’s buggy under IE7 on >=Vista…

thx for this article and especially the demo. whenever I have to make a gradient I go to your demo and copy the code. thats very useful!

It seems this fallback works not only with gradients, but with RGBA backgrounds too. E.g. when you want a semi-transparent background, you can use

Firefox 3.6 won’t download the background image.

Thanks for the great post.

FYI, I’ve seen a small typo on the “view demo” link on top, /examples/CSS3Gradient/ at that page you have same webkit properties for two gradients even though the gradients differ.

Great post! I learned a little more about CSS 3 gradients.

-webkit-gradient(linear, 0 0, 0 100, from(#0f82f7), to(#072727));

-webkit-gradient(linear, 0% 0%, 0% 100%, from(#0f82f7), to(#072727));

gradient will not stretch.

You can use SVG for fallback as following: background-image:url('data:image/svg+xml,'); I.e. write usual SVG as data:url, you only need to replace „#“ with „%23“. Pros: you can modify gradients right in CSS. Cons: very large syntax.

Wrong code, the right one: background-image:url(‘data:image/svg+xml,<svg xmlns=”http://www.w3.org/2000/svg”><defs><linearGradient id=”g” x2=”0″ y2=”100%”><stop offset=”0″ stop-color=”%232F2727″/><stop offset=”100%” stop-color=”%231a82f7″/></linearGradient></defs><rect width=”100%” height=”100%” style=”fill:url(%23g)”/></svg>’);

I don’t get it. If an image isn’t supported, why would you add another image?

Thank you! You just saved me about thirteen months of trying to figure this out on my own!

CSS gradients are finally supported pretty well, thanks for the heads up.

Just one thing, Mozilla is not a rendering engine, it’s called Gecko.

Well then, to add to Sunny Singh’s comment, Opera is not a rendering engine, it’s called Presto (layout engine). =)

I’m using CSS3 Gradients, Opera, Safari and Mozilla supports them great..

I use a gradient generator, that generates moz and webkit gradient, and a filter for IE.. but still I delete the filter for IE, and go for images..

Yes, the CSS will get huge when I need to specify 3-4 backgrounds each time for same element.. But it’s not the same size as what the background image would be, and I write my code nice, so easy to update, I save the requests on the browsers that support it, and some traffic.. So why not use them, I’m just thinking..

If possible, I’ll never open photoshop when creating sites.. because I can code the graphics I need, and for fixing Chrome, and IE etc.. I take a lovely screenie on the site.. Starting slicing the graphics out in Preview in mac.. works great.. and then I optimize the images after so it works perfect :)

It’s my way to create websites.. and they’re kinda fast :)

If you include fallback images as data uri, all browsers will load it and skip css gradients. Adding !important to gradient declarations forces browsers to use it. In addition, in IE9 if you use IE filters and rounded corners it just doesnt work. IE9 wont clip background to the border. A simple workaround is to declare gradients for supported browsers and fallback image in IE condidional stylesheet. IE performance will suffer, but that’s just the price for using poor browser.

Another great tricks here.. the demo is good, hope to download the source code so I could test it right away.

I’ve recently started using CSS gradients and aside from the browser specific syntax ( http://www.colorzilla.com/gradient-editor/ helps a lot) they work great.

The biggest advantage over sprites is that they’re vertically scalable. Even IE6 works just fine with linear gradients, which is probably the most common use for them.

I’m using gradients on the menu for our website. I wanted to cut down image use to as little as possible using CSS3 techniques (many learned from you). The result for me is actually a website far more visually stimulating, satisfying and successful in its objectives then when I had the full blown power of Photoshop available to me. Not using images at all is arguably more restricting but then its implementation has almost forced me to create a more clean and functional design that isn’t overly cluttered with visual goodies.

Fallback wise, I’m sticking to solid color however.

Where did you find Opera 11.10?

Link in the footer of Opera.com

Here’s an interesting article I found on using SVG to get gradients to work in IE9 in a non ms-filter way

http://css3wizardry.com/2010/10/29/css-gradients-for-ie9/

Haven’t tried it yet, don’t know how it affects HTTP requests, and may just add an unnecessary layer of complexity, but may be worth investigating?

I’m glad to see you didn’t use the IE9 SVG fix for using gradients. I believe an anternative (old-school) background image will do just fine.

Thats the right solution, thx and i also works for my new sites. I alway searched for and there was no solution in pagespeed.

i have been trying to make a gradient background work for a site i’ve been drafting… but i haven’t found much in the way of cross-browser support. http://www.denisebeaudet.com/new-index.html

for example: this works fine in FF4 on a mac and is *non-existent* for FF4 for Windows. annoying.

the other thing that is quite bothersome is the buggy aspect where if your browser window is set at something less than full-screen, and you then scroll to see what is “below the fold” (i.e. below the viewport bottom-margin), it reverts to the startcolor. very annoying and visually interruptive.

ideas? please?

using the correct code would probably help. you left out the new syntax for Chrome, you don’t really need the old syntax for Chrome(IMHO) because Chrome auto updates. you’re also using svg for opera, why? gradients are supported in opera.

Go back through this article and re-read everything, you’ll see your problems pretty quickly.

Well it will certainly speed up one’s site. But what about the compatibility issues. For IE we need to use the js code for getting the bg gradient.

Thank you for this article. I am using some gradients on my latest site. It works great. Sadly there are still people browsing with IE6 on my sites. But with only 3% I am one of the lucky guys.

Awesome!!! Thanks for the breakdown!

Really cool trick here I didn’t know how to do. I’m think I’m going to go ahead and give it a go on one of my sites.

Just a note: although you have dismissed IE, I can’t since 95% of our visitors use IE7-9. I have found that simple linear gradients ca be used as follows:

filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=’#FFFAE5′, endColorstr=’#FFDB95′);

Hope this helps some users who must live in the real world.

The web just got a whole lot more colorful. I have a tool that will generate the css for any linear gradient – and create the gradient even on IE6 using a simple behavior file i wrote for IE.

Enjoy (see the link in my contact info)! Ron

Great resource and tips for gradients. Although, I’ve been working on adding noise to a CSS gradient and didn’t find much help online so I wanted to share my solution.

Wow! CSS3 is like magic! Thanks for this tutorial!

You can cover nearly 100% of gradient-supporting browsers with just two lines:

The first line is realistically only needed for iOS 6-, Safari 6.1-, and Android 4.3-.

As you pointed out, filter for IE is gross (btw it’s not just about performance — it also turns off ClearType) so you need fallback images if your gradients are critical and not strictly decorational.

Those fallback images will also cover the extremely tiny percentage of browsers that still need prefixes, such as old versions of desktop Opera ( -o- ), Konquerer ( -khtml- ), and people who are not getting auto-updates for Chrome and Firefox (hardly anyone, according to StatCounter).

There’s no help for Opera Mini (where we’d want to avoid the HTTP request for the image) since it doesn’t support linear-gradient with or without a prefix.

A lot of sites include the -ms- variation but that was only necessary for one developer preview of IE 10, not any public release.

Tiny clarification points:

Remember to be very careful about the tweener syntax. For your top-to-bottom example, that will be fine, but I wouldn’t want people to think, oh I’ll just handle the prefixing myself with the syntax I already know… and do this:

Because that isn’t going to work. The unprefixed version there is using the tweener syntax and breaking it. You’ll need to do:

which I personally found hard to remember at easy to screw up.

Also, I’m not sure there was ever a public browser that needed -khtml- for gradients, was there?

Great new tools: Gradient Generator

Please don’t take it personally. I still prefer the background image version for now. Anyway, I can still set the image size to 1 pixel width, and turn it into base64 version.

Rather using an actual image file, is better for control and performance .

Better for control, but maybe not for performance. Using CSS gradients (especially multiple CSS gradient) makes the web pages heavy scrolled.

CSS gradients probably only suitable if used for scallable gradient on the container size that is not fixed. In fact, I more often make gradations for a fixed size, or specific height then leaving the rest as plain color without gradations.

I would have to see some real tests that prove that image gradients are better for scrolling performance. Do you have one available? I’m sure it’s possible but I don’t like throwing statements like that around.

Sorry. Different operating systems might yield in different results. At least that’s what I feel (slow). By searching for keyword CSS3+gradient+slow+scroll on Google , I get some of this link:

http://stackoverflow.com/a/4023133/1163000 https://bugzilla.mozilla.org/show_bug.cgi?id=657603 http://yannesposito.com/Scratch/en/blog/2010-07-07-CSS-rendering-problems-by-navigator http://www.tricedesigns.com/2013/03/11/performance-ux-considerations-for-successful-phonegap-apps (see on Keep Graphics Simple )

As a live example, you can try to visit http://lea.verou.me/css3patterns with quite small screen then scroll down and feel. Then click on Carbon or Carbon Fibre pattern then scroll again and feel.

Example image patterns site with better scroll performance: http://subtlepatterns.com

CodePen example: Background Image vs. CSS3 Gradient

I’m surprised no-one’s mentioned CSS3Pie yet which does a pretty good job of bringing CSS3 gradients to older IE browsers.

CSS3 pie uses IE filers as well to accomplish the gradients in old IE, but we can write them ourself (if we really, really have to).

I have had issues with color fallback support using background or background-image specifically with IE7 and IE8. Thus, I write my code starting like this:

http://codepen.io/anon/pen/cuCql

Instead of two background properties for fallback and svg, put them on one line. This works flawlessly for oldIE and svg works for IE9.

I usually don’t come here to comment, but this article is so complete and thoughtful, that I had to say thank you: thank you man!

Its awesome. But it doesn’t work on ie9. Do you have any rule for ie9?

Great update on the new way for CSS Gradients Chris.. you did a really a great and thorough job, keep up the great work!

Here’s something I always use to generate them for me: http://colorzilla.com/gradient-editor/ .

It will generate the CSS for you with optional IE9 support.

I think using image instead of css properties has their cons and pros. First, using css for making gradient makes it harder to get it works in old browsers and computers. I normally tend to use photoshop instead of css properties for gradient. Using css is fast without need to use a third party software like photoshop or other graphics programs.

this is what i use (with LESS):

And then just call this wherever I need the gradient as background:

There is a mistake in the article. Since version 11.60 Opera is supporting the new “to” syntax for gradients. And since 12.10 gradient properties are unprefixed. They wouldn’t be unprefixed if they had deprecated, different from standardized, syntax. The latest Presto based Opera has support for every gradient related function (linear and radial, optionally repeating) and is compatible with W3C standards in that regard.

So the proper list would be: 11.00-: No support 11.10-11.50: Tweener, prefixed, only linear 11.60-12.00: New and legacy tweener , prefixed, added radial 12.10-12.16, 15+: New , unprefixed

Version 12.16 is still being used, so it is relevant.

(Also a small typo: “repeating liner gradients”)

Whoa! This is the first time I’m hearing about RADIAL gradient. That’s pretty awesome stuff. I’m definitely going to try it out. To be honest I once remembered how to write a pretty much completely cross browser friendly gradient. But now I just use an online tool to generate the whole thing for me.

Yeah agreed. Pretty cool that you can create something like that and get rid of all those images. It’s also great to see that a lot of the browsers do not require vendor prefixes anymore. Certainly reduces file sizes.

Great Demo, I was looking for a comprehensive script to implement on our new design for a blue sky gradient. I hope there wont be limitations on some browsers.

Don’t like to think about requirements like possible fallbacks. Hopefully i can forget about less and stuff like these one day and be more modern and intuitive. We are on the right way. Anyway “repeating-radial-gradient” was new for me.

Awesome that you can specify degrees and do radial gradients too.

IMAGES

  1. CSS linear-gradient() Function

    css linear gradient transparent safari

  2. 【CSS】linear-gradientの使い方【値、角度など】

    css linear gradient transparent safari

  3. CSS linear-gradient 实现背景双色或多色,颜色渐变,颜色分明_linear-gradient 设置多重线条背景颜色-CSDN博客

    css linear gradient transparent safari

  4. CSS gradients

    css linear gradient transparent safari

  5. Exploring the Power of Css Linear Gradient Generator

    css linear gradient transparent safari

  6. How to create gradient border with Tailwind CSS

    css linear gradient transparent safari

VIDEO

  1. Affordable Bomb Proof Arrows

  2. CSS Linear Gradient

  3. css linear-gradient #culture coding

  4. Verläufe mit CSS3

  5. CSS Linear Gradients

  6. CSS linear gradient and radial gradient ...#coding #webdeveloper #css #htmlcssjs #fiverr

COMMENTS

  1. css

    I am having trouble showing a linear gradient in Safari and Chrome. In Firefox it shows up fine. I am trying: background: -webkit-linear-gradient(center top , #9E9E9E, #454545) repeat scroll 0 0 transparent; background: -moz-linear-gradient(center top , #9E9E9E, #454545) repeat scroll 0 0 transparent; background: -ms-linear-gradient(center top , #9E9E9E, #454545) repeat scroll 0 0 transparent ...

  2. css

    49. This has to do with the way browsers render transparent. For most browsers, transparent === rgba(255,255,255,0) But Safari renders it as. transparent === rgba(0,0,0,0) So if you have a gradient from transparent to white (or rgba(255,255,255,1) ), for most browsers you're only changing the alpha from 0 to 1 along the gradient. But for Safari ...

  3. 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 ...

  4. Complete Guide To Cross Browser Compatible CSS Gradients

    Radial CSS Gradients enjoy the same browser support as CSS Linear Gradients that we discussed above, offering great cross browser compatibility. All modern browsers like Google Chrome, Mozilla Firefox, Opera, Safari and Edge support radial CSS gradients. The only exception is in Internet explorer IE 6-9.

  5. A Thing To Know about Gradients and "Transparent Black"

    The element on the left in each browser demonstrates the problem. The problem, the best I understand it, is that transparent is being interpreted (and interpolated) as "transparent black". To fix it, you have to set the color as a fully transparent version of that exact color. Like: .element {. background: linear-gradient(.

  6. Safari bug with gradients that fade to "transparent"

    CSS. .element { background: linear-gradient (. to bottom, red, transparent ); } There is a pretty big gotcha here, though. In Chrome (also Android), Firefox, and Edge, you'd be all good. But in Safari (also iOS), you'd not be good. The element on the left in each browser demonstrates the problem. The problem, the best I understand it, is ...

  7. CSS background gradient to transparent color on Safari

    About CSS Preprocessors. CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions. ... { width: 400px; height: 400px; margin: 50px auto; } .box--transparent-1 { background: linear-gradient(0deg, red, transparent); } .box--transparent-2 { background: linear-gradient ...

  8. Safari CSS Visual Effects Guide

    Safari CSS Visual Effects Guide. 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 ...

  9. How to Set Transparency with Linear Gradient in CSS

    In this approach, first create a centered box with a linear gradient background using HSLA colors, which allows for transparency. The gradient transitions from red (hue 0) to blue (hue 240) with 50% saturation and lightness, while the alpha value (0.5) controls the transparency level. Example: Illustration of transparency with Linear Gradient ...

  10. Using CSS gradients

    Using CSS gradients. CSS gradients are represented by the <gradient> data type, a special type of <image> made of a progressive transition between two or more colors. You can choose between three types of gradients: linear (created with the linear-gradient() function), radial (created with the radial-gradient() function), and conic (created ...

  11. Radial Gradient Recipes

    To safari transparent means rgba(0,0,0,0) which can cause faulty values in between the start and end color as the colors are computed towards black and transparent (in that order). For example: Halfway the linear gradient from rgba(255,255,255,1) to transparent gives you rgba(127,127,127,0.5) instead of rgba(255,255,255,0.5)

  12. Linear Gradients

    CSS Linear Gradients. What is a Linear Gradient? Probably the most common and used type of gradient is the linear-gradient (). To create a linear gradient you must define at least two colors (or color-stops), and their value can be any type of color format (e.g. Hex, named colors, rgba, hsla, etc.). The gradient direction can be specified as a ...

  13. CSS Gradients Guide

    Linear CSS gradients. Perhaps the most common type of CSS gradient we see in web design is the ... Safari; 10* 36: 10: 12: 15.4: Mobile / Tablet. Android Chrome Android Firefox Android iOS Safari; 128: 127: 4* 15.4: Related articles . Article on Jan 10, 2017 A Thing To Know about Gradients and "Transparent Black" Chris Coyier . Article on ...

  14. CSS3 Gradients

    -webkit-repeating-radial-gradient(top left, circle, red, blue 10%, red 20%) Changes from -webkit-gradient. You should be able to recreate most of the gradients you made with -webkit-gradient with this new syntax, but there are some changes to be aware of.. First, -webkit-gradient uses a two-point syntax that lets you explicitly state where a linear gradient starts and ends.

  15. Easing Linear Gradients

    Here's an example that shows how harsh a standard linear-gradient() can be compared to how smooth we can make it by easing it: Screencap from "The Good, the Bad and the Ugly" with gradients overlaid. Il buono (the good): Smooth gradients in CSS that blends into their context. Il cattivo (the bad): No text protection (bad accessibility).

  16. css

    The following CSS doesn`t function on Safari (tested on iPad iOS): .map-left-navi { background: #ffffff; background: -moz-linear-gradient(left, #ffffff 35%, transparent 100%); backgrou...

  17. CSS Gradients

    Just as you can declare the background of an element to be a solid color in CSS, you can also declare that background to be a gradient. Using gradients declared in CSS, rather using an actual image file, is better for control and performance. Gradients are typically one color that fades into another, but in CSS you can control every aspect of how that happens, from the direction to the colors ...