CSS Image Values and Replaced Content Module Level 3

Editor’s Draft,

This version:
https://drafts.csswg.org/css-images-3/
Latest published version:
https://www.w3.org/TR/css3-images/
Previous Versions:
https://www.w3.org/TR/2012/CR-css3-images-20120417/
https://www.w3.org/TR/2012/WD-css3-images-20120112/
Test Suite:
http://test.csswg.org/suites/css-images-3_dev/nightly-unstable/
Issue Tracking:
Tracker
Inline In Spec
GitHub Issues
Editors:
Tab Atkins Jr. (Google)
Elika J. Etemad / fantasai (Invited Expert)

Abstract

This module contains the features of CSS level 3 relating to the <image> type and replaced elements. It includes and extends the functionality of CSS level 2 [CSS21]. The main extensions compared to CSS2.1 are the generalization of the <url> type to the <image> type, several additions to the <image> type, a generic sizing algorithm for images and other replaced content in CSS, definitions for interpolating several <image> types, and several properties controlling the interaction of replaced elements and CSS’s layout models.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, in speech, etc.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

GitHub Issues are preferred for discussion of this specification. When filing an issue, please put the text “css-images” in the title, preferably like this: “[css-images] …summary of comment…”. All issues and comments are archived, and there is also a historical archive.

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 1 September 2015 W3C Process Document.

1. Introduction

This section is not normative.

In CSS Levels 1 and 2, image values, such as those used in the background-image property, could only be given by a single URL value. This module introduces additional ways of representing 2D images, for example as a URL with color fallback or as a gradient.

This module also defines several properties for manipulating raster images and for sizing or positioning replaced elements such as images within the box determined by the CSS layout algorithms. It also defines in a generic way CSS’s sizing algorithm for images and other replaced elements.

2. Image Values: the <image> type

The <image> value type denotes a 2D image. It can be a url reference, image notation, or gradient notation. Its syntax is:

<image> = <url> | <image()> | <image-set()> | <element()> | <cross-fade()> | <gradient>

An <image> can be used in many CSS properties, including the background-image, list-style-image, cursor properties [CSS21] (where it replaces the <url> component in the property’s value).

In some cases, an image is invalid, such as a <url> pointing to a resource that is not a valid image format. An invalid image is rendered as a solid-color transparent image with no intrinsic dimensions. However, invalid images have special behavior in some contexts, such as the image() notation.

2.1. Image References and Image Slices: the <url> type and url() notation

The simplest way to indicate an image is to reference an image file by URL. This can be done with the url() notation, defined in [css-values-3].

In the example below, a background image is specified with url()syntax:
background-image: url(wavy.png);

If the UA cannot download, parse, or otherwise successfully display the contents at the URL as an image, it must be treated as an invalid image.

2.2. Image Fallbacks and Annotations: the image() notation

The image() function allows an author to:

The image() notation is defined as:

image() = image( [ [ <image> | <string> ]? , <color>? ]! )

A <string> used in image() represents a <url>. As usual for URLs in CSS, relative URLs are resolved to an absolute URL (as described in Values & Units [css-values-3]) when a specified image() value is computed.

If the image has an orientation specified in its metadata, such as EXIF, the UA must rotate or flip the image to correctly orient it as the metadata specifies.

2.2.1. Image Fallbacks

If both a URL and a <color> are specified in image(), then whenever the URL represents an invalid image, the image() function renders as if the URL were not specified at all; it generates a solid-color image as specified in §2.2.3 Solid-color Images.

The fallback color can be used to ensure that text is still readable even when the image fails to load. For example, the following legacy code works fine if the image is rectangular and has no transparency:
body      { color: black; background: white; }
p.special { color: white; background: url("dark.png") black; }

When the image doesn’t load, the background color is still there to ensure that the white text is readable. However, if the image has some transparency, the black will be visible behind it, which is probably not desired. The image() function addresses this:

body      { color: black; background: white; }
p.special { color: white; background: image("dark.png", black); }

Now, the black won’t show at all if the image loads, but if for whatever reason the image fails, it’ll pop in and prevent the white text from being set against a white background.

2.2.2. Image Fragments

When a URL specified in image() represents a portion of a resource (e.g. by the use of media fragment identifiers) that portion is clipped out of its context and used as a standalone image.

For example, given the following image and CSS:

[9 circles, with 0 to 8 eighths filled in]

background-image: image('sprites.svg#xywh=40,0,20,20')

...the background of the element will be the portion of the image that starts at (40px,0px) and is 20px wide and tall, which is just the circle with a quarter filled in.

So that authors can take advantage of CSS’s forwards-compatible parsing rules to provide a fallback for image slices, implementations that support the image() notation must support the xywh=#,#,#,# form of media fragment identifiers for images specified via image(). [MEDIA-FRAGS]

Note that image fragments can also be used with the url() notation. However, a legacy UA that doesn’t understand the media fragments notation will ignore the fragment and simply display the entirety of the image.

Since the image() notation requires UAs to support media fragments, authors can take advantage of CSS’s forward-compatible parsing rules to provide a fallback when using an image fragment URL:

background-image: url('swirl.png'); /* old UAs */
background-image: image('sprites.png#xywh=10,30,60,20'); /* new UAs */

If a URL uses a fragment identifier syntax that the implementation does not understand, or does not consider valid for that type of image, the URL must be treated as representing an invalid image.

Note: This error-handling is limited to image(), and not in the definition of URL, for legacy compat reasons.

2.2.3. Solid-color Images

If the image() function is specified with only a <color> argument (no URL), it represents a solid-color image of the specified color with no intrinsic dimensions.

For example, one can use this as a simple way to "tint" a background image, by overlaying a partially-transparent color over the top of the other image:
background-image: image(rgba(0,0,255,.5)), url("bg-image.png");

background-color does not work for this, as the solid color it generates always lies beneath all the background images.

2.3. Resolution Negotiation: the image-set() notation

Delivering the most appropriate image resolution for a user’s device can be a difficult task. Ideally, images should be in the same resolution as the device they’re being viewed in, which can vary between users. However, other factors can factor into the decision of which image to send; for example, if the user is on a slow mobile connection, they may prefer to receive lower-res images rather than waiting for a large proper-res image to load. The image-set() function allows an author to ignore most of these issues, simply providing multiple resolutions of an image and letting the UA decide which is most appropriate in a given situation.

This solution assumes that resolution is a proxy for filesize, and therefore doesn’t appropriately handle multi-resolution sets of vector images, or mixing vector images with raster ones (e.g. for icons). For example, use a vector for high-res, pixel-optimized bitmap for low-res, and same vector again for low-bandwidth (because it’s much smaller, even though it’s higher resolution).

The syntax for image-set() is:

image-set() = image-set( <image-set-option># )
<image-set-option> = [ <image> | <string> ] <resolution>

We should add "w" and "h" dimensions as a possibility, and a "format()" function, to match the functionality of HTML’s picture.

The image-set() function can not be nested inside of itself, either directly or indirectly (as an argument to another <image> type).

Is this restriction needed?

Each <string> inside image-set() represents a <url>, just like in image().

Every <image-set-option> in a given image-set() must have a different <resolution>, or else the function is invalid.

UAs must make a UA-specific choice of which <image-set-option> to load, based on whatever criteria they find relevant (such as the resolution of the display, connection speed, etc). The image-set() then represents the image associated with the URL of that choice. The image’s intrinsic resolution is the resolution associated with that choice. UAs may change which <image-set-option> they wish to use for a given image-set() over the lifetime of the page, if the criteria used to determine which option to choose change significantly enough to make it worthwhile in the UA’s estimation.

This example shows how to use image-set() to provide an image in three versions: a "normal" version, a "high-res" version, and an extra-high resolution version for use in high-quality printing (as printers can have extremely high resolution):
background-image: image-set( "foo.png" 1x,
                             "foo-2x.png" 2x,
                             "foo-print.png" 600dpi );

2.4. Combining images: the cross-fade() notation

When transitioning between images, CSS requires a way to explicitly refer to the intermediate image that is a combination of the start and end images. This is accomplished with the cross-fade() function, which indicates the two images to be combined and how far along in the transition the combination is.

Note: Authors can also use the cross-fade() function for many simple image manipulations, such as tinting an image with a solid color or highlighting a particular area of the page by combining an image with a radial gradient.

The syntax for cross-fade() is defined as:

cross-fade() = cross-fade( <cf-mixing-image> , <cf-final-image>? )
<cf-mixing-image> = <percentage>? && <image>
<cf-final-image> = <image> | <color>

The function represents an image generated by combining two images.

The <percentage> represents how much of the first image is retained when it is blended with the second image. The <percentage> must be between 0% and 100% inclusive; any other value is invalid. If omitted, it defaults to the value 50%.

If the last argument is a <color>, it represents a solid-color image with the same intrinsic dimensions as the first image (as if it were an image() function with the color as its sole argument). If omitted, it defaults to the color transparent.

More precisely, given cross-fade(p A, B), where A and B are images and p is a percentage between 0% and 100%, the function represents an image with width equal to widthA × p + widthB × (1-p) and height equal to heightA × p + heightB × (1-p). The contents of the image must be constructed by first scaling A and B to the size of the generated image, then applying dissolve(A,p) plus dissolve(B,1-p). The "dissolve()" function and "plus" compositing operator are defined in the literature by Porter-Duff. [PORTERDUFF]

3. Gradients

A gradient is an image that smoothly fades from one color to another. These are commonly used for subtle shading in background images, buttons, and many other things. The gradient notations described in this section allow an author to specify such an image in a terse syntax, so that the UA can generate the image automatically when rendering the page. The syntax of a <gradient> is:

<gradient> =
  <linear-gradient()> | <repeating-linear-gradient()> |
  <radial-gradient()> | <repeating-radial-gradient()>

As with the other <image> types defined in this specification, gradients can be used in any property that accepts images. For example:

A gradient is drawn into a box with the dimensions of the concrete object size, referred to as the gradient box. However, the gradient itself has no intrinsic dimensions.

For example, if you use a gradient as a background, by default the gradient will draw into a gradient box the size of the element’s padding box. If background-size is explicitly set to a value such as 100px 200px, then the gradient box will be 100px wide and 200px tall. Similarly, for a gradient used as a list-style-image, the box would be a 1em square, which is the default object size for that property.

Gradients are specified by defining the starting point and ending point of a gradient line (which, depending on the type of gradient, may be technically a line, or a ray, or a spiral), and then specifying colors at points along this line. The colors are smoothly blended to fill in the rest of the line, and then each type of gradient defines how to use the color of the gradient line to produce the actual gradient.

3.1. Linear Gradients: the linear-gradient() notation

A linear gradient is created by specifying a straight gradient line, and then several colors placed along that line. The image is constructed by creating an infinite canvas and painting it with lines perpendicular to the gradient line, with the color of the painted line being the color of the gradient line where the two intersect. This produces a smooth fade from each color to the next, progressing in the specified direction.

3.1.1. linear-gradient() syntax

The linear gradient syntax is:

linear-gradient() = linear-gradient(
  [ <angle> | to <side-or-corner> ]? ,
  <color-stop-list>
)
<side-or-corner> = [left | right] || [top | bottom]

The first argument to the function specifies the gradient line, which gives the gradient a direction and determines how color-stops are positioned. It may be omitted; if so, it defaults to to bottom.

The gradient line’s direction may be specified in two ways:

using angles

For the purpose of this argument, 0deg points upward, and positive angles represent clockwise rotation, so 90deg point toward the right.

using keywords

If the argument is to top, to right, to bottom, or to left, the angle of the gradient line is 0deg, 90deg, 180deg, or 270deg, respectively.

If the argument instead specifies a corner of the box such as to top left, the gradient line must be angled such that it points into the same quadrant as the specified corner, and is perpendicular to a line intersecting the two neighboring corners of the gradient box. This causes a color-stop at 50% to intersect the two neighboring corners (see example).

Starting from the center of the gradient box, extend a line at the specified angle in both directions. The ending point is the point on the gradient line where a line drawn perpendicular to the gradient line would intersect the corner of the gradient box in the specified direction. The starting point is determined identically, but in the opposite direction.

Given:

The length of the gradient line (between the starting point and ending point) is:

abs(W * sin(A)) + abs(H * cos(A))

Note: It is expected that the next level of this module will provide the ability to define the gradient’s direction relative to the current text direction and writing-mode.

[An image showing a box with a background shading gradually from white in the bottom-left corner to black in the top-right corner.  There is a line, illustrating the gradient line, angled at 45 degrees and passing through the center of the box.  The starting point and ending point of the gradient line are indicated by the intersection of the gradient line with two additional lines that pass through the bottom-left and top-right corners of the box.]

This example illustrates visually how to calculate the gradient line from the rules above. This shows the starting and ending point of the gradient line, long with the actual gradient, produced by an element with background: linear-gradient(45deg, white, black);.

Notice how, though the starting point and ending point are outside of the box, they’re positioned precisely right so that the gradient is pure white exactly at the corner, and pure black exactly at the opposite corner. That’s intentional, and will always be true for linear gradients.

Given:

The length of the gradient line (between the starting and ending point) is: abs(W * sin(A)) + abs(H * cos(A))

The gradient’s color stops are typically placed between the starting point and ending point on the gradient line, but this isn’t required - the gradient line extends infinitely in both directions. The starting point and ending point are merely arbitrary location markers - the starting point defines where 0%, 0px, etc are located when specifying color-stops, and the ending point defines where 100% is located. Color-stops are allowed to have positions before 0% or after 100%.

The color of the gradient at any point is determined by finding the unique line passing through that point that is perpendicular to the gradient line. The point’s color is the color of the gradient line at the point where this line intersects it.

3.1.2. Linear Gradient Examples

All of the following linear-gradient() examples are presumed to be backgrounds applied to a box that is 200px wide and 100px tall.

Below are various ways of specifying a basic vertical gradient:
linear-gradient(yellow, blue);
linear-gradient(to bottom, yellow, blue);
linear-gradient(180deg, yellow, blue);
linear-gradient(to top, blue, yellow);
linear-gradient(to bottom, yellow 0%, blue 100%);

This demonstrates the use of an angle in the gradient. Note that, though the angle is not exactly the same as the angle between the corners, the gradient line is still sized so as to make the gradient yellow exactly at the upper-left corner, and blue exactly at the lower-right corner.
linear-gradient(135deg, yellow, blue);
linear-gradient(-45deg, blue, yellow);

This demonstrates a 3-color gradient, and how to specify the location of a stop explicitly:

linear-gradient(yellow, blue 20%, #0f0);

This demonstrates a corner-to-corner gradient specified with keywords. Note how the gradient is red and blue exactly in the bottom-left and top-right corners, respectively, exactly like the second example. Additionally, the angle of the gradient is automatically computed so that the color at 50% (in this case, white) stretches across the top-left and bottom-right corners.
linear-gradient(to top right, red, white, blue)
(Image requires SVG)

3.2. Radial Gradients: the radial-gradient() notation

In a radial gradient, rather than colors smoothly fading from one side of the gradient box to the other as with linear gradients, they instead emerge from a single point and smoothly spread outward in a circular or elliptical shape.

A radial gradient is specified by indicating the center of the gradient (where the 0% ellipse will be) and the size and shape of the ending shape (the 100% ellipse). Color stops are given as a list, just as for linear-gradient(). Starting from the gradient center and progressing towards (and potentially beyond) the ending shape uniformly-scaled concentric ellipses are drawn and colored according to the specified color stops.

3.2.1. radial-gradient() Syntax

The radial gradient syntax is:

radial-gradient() = radial-gradient(
  [ <ending-shape> || <size> ]? [ at <position> ]? ,
  <color-stop-list>
)
Here is an example of a circular radial gradient 5em wide and positioned with its center in the top left corner:
radial-gradient(5em circle at top left, yellow, blue)

We should add the ability to move the focus of the gradient, as in the original -webkit-gradient() function. See proposal in http://lists.w3.org/Archives/Public/www-style/2011Nov/0210.html for "from <position>" and "from offset <offset>".

The arguments are defined as follows:

<position>
Determines the gradient center of the gradient. The <position> value type (which is also used for background-position) is defined in [css-values-3], and is resolved using the center-point as the object area and the gradient box as the positioning area. If this argument is omitted, it defaults to center.
<ending-shape>
Can be either circle or ellipse; determines whether the gradient’s ending shape is a circle or an ellipse, respectively. If <ending-shape> is omitted, the ending shape defaults to a circle if the <size> is a single <length>, and to an ellipse otherwise.
<size>
Determines the size of the gradient’s ending shape. If omitted it defaults to farthest-corner. It can be given explicitly or by keyword. For the purpose of the keyword definitions, consider the gradient box edges as extending infinitely in both directions, rather than being finite line segments.

If the ending-shape is an ellipse, its axises are aligned with the horizontal and vertical axises.

Both circle and ellipse gradients accept the following keywords as their <size>:

closest-side
The ending shape is sized so that it exactly meets the side of the gradient box closest to the gradient’s center. If the shape is an ellipse, it exactly meets the closest side in each dimension.
farthest-side
Same as closest-side, except the ending shape is sized based on the farthest side(s).
closest-corner
The ending shape is sized so that it passes through the corner of the gradient box closest to the gradient’s center. If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified.
farthest-corner
Same as closest-corner, except the ending shape is sized based on the farthest corner. If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.

If <ending-shape> is specified as circle or is omitted, the <size> may be given explicitly as:

<length>
Gives the radius of the circle explicitly. Negative values are invalid.

Note: Percentages are not allowed here; they can only be used to specify the size of an elliptical gradient, not a circular one. This restriction exists because there is are multiple reasonable answers as to which dimension the percentage should be relative to. A future level of this module may provide the ability to size circles with percentages, perhaps with more explicit controls over which dimension is used.

If <ending-shape> is specified as ellipse or is omitted, <size> may instead be given explicitly as:

<length-percentage>{2}
Gives the size of the ellipse explicitly. The first value represents the horizontal radius, the second the vertical radius. Percentages values are relative to the corresponding dimension of the gradient box. Negative values are invalid.
Expanded with the above definitions, the grammar becomes:
radial-gradient() = radial-gradient(
  [ [ circle               || <length> ]                          [ at <position> ]? , |
    [ ellipse              || <length-percentage>{2} ]            [ at <position> ]? , |
    [ [ circle | ellipse ] || <extent-keyword> ]                  [ at <position> ]? , |
    at <position> ,
  ]?
  <color-stop> [ , <color-stop> ]+
)
<extent-keyword> = closest-corner | closest-side | farthest-corner | farthest-side

3.2.2. Placing Color Stops

Color-stops are placed on a gradient line shaped like a ray (a line that starts at one point, and extends infinitely in a one direction), similar to the gradient line of linear gradients. The gradient line’s starting point is at the center of the gradient, and it extends toward the right, with the ending point on the point where the gradient line intersects the ending shape. A color-stop can be placed at a location before 0%; though the negative region of the gradient line is never directly consulted for rendering, color stops placed there can affect the color of non-negative locations on the gradient line through interpolation or repetition (see repeating gradients). For example, radial-gradient(red -50px, yellow 100px) produces an elliptical gradient that starts with a reddish-orange color in the center (specifically, #f50) and transitions to yellow. Locations greater than 100% simply specify a location a correspondingly greater distance from the center of the gradient.

The color of the gradient at any point is determined by first finding the unique ellipse passing through that point with the same center, orientation, and ratio between major and minor axises as the ending-shape. The point’s color is then the color of the positive section of the gradient line at the location where this ellipse intersects it.

3.2.3. Degenerate Radial Gradients

Some combinations of position, size, and shape will produce a circle or ellipse with a radius of 0. This will occur, for example, if the center is on a gradient box edge and closest-side or closest-corner is specified or if the size and shape are given explicitly and either of the radiuses is zero. In these degenerate cases, the gradient must be be rendered as follows:

If the ending shape is a circle with zero radius:

Render as if the ending shape was a circle whose radius was an arbitrary very small number greater than zero. This will make the gradient continue to look like a circle.

If the ending shape has zero width (regardless of the height):

Render as if the ending shape was an ellipse whose height was an arbitrary very large number and whose width was an arbitrary very small number greater than zero. This will make the gradient look similar to a horizontal linear gradient that is mirrored across the center of the ellipse. It also means that all color-stop positions specified with a percentage resolve to 0px.

Otherwise, if the ending shape has zero height:

Render as if the ending shape was an ellipse whose width was an arbitrary very large number and whose height was an arbitrary very small number greater than zero. This will make the gradient look like a solid-color image equal to the color of the last color-stop, or equal to the average color of the gradient if it’s repeating.

3.2.4. Radial Gradient Examples

All of the following examples are applied to a box that is 200px wide and 100px tall.

These examples demonstrate different ways to write the basic syntax for radial gradients:
radial-gradient(yellow, green);
radial-gradient(ellipse at center, yellow 0%, green 100%);
radial-gradient(farthest-corner at 50% 50%, yellow, green);

radial-gradient(circle, yellow, green);

radial-gradient(red, yellow, green);

This image shows a gradient originating from somewhere other than the center of the box:
radial-gradient(farthest-side at left bottom, red, yellow 50px, green);

Here we illustrate a closest-side gradient.
radial-gradient(closest-side at 20px 30px, red, yellow, green);
radial-gradient(20px 30px at 20px 30px, red, yellow, green);

radial-gradient(closest-side circle at 20px 30px, red, yellow, green);
radial-gradient(20px 20px at 20px 30px, red, yellow, green);

3.3. Repeating Gradients: the repeating-linear-gradient() and repeating-radial-gradient() notations

In addition to linear-gradient() and radial-gradient(), this specification defines repeating-linear-gradient() and repeating-radial-gradient() values. These notations take the same values and are interpreted the same as their respective non-repeating siblings defined previously.

When rendered, however, the color-stops are repeated infinitely in both directions, with their positions shifted by multiples of the difference between the last specified color-stop’s position and the first specified color-stop’s position. For example, repeating-linear-gradient(red 10px, blue 50px) is equivalent to linear-gradient(..., red -30px, blue 10px, red 10px, blue 50px, red 50px, blue 90px, ...). Note that the last color-stop and first color-stop will always coincide at the boundaries of each group, which will produce sharp transitions if the gradient does not start and end with the same color.

Repeating gradient syntax is identical to that of non-repeating gradients:
repeating-linear-gradient(red, blue 20px, red 40px)

repeating-radial-gradient(red, blue 20px, red 40px)

repeating-radial-gradient(circle closest-side at 20px 30px, red, yellow, green 100%, yellow 150%, red 200%)

If the gradient has only a single color-stop, it must render as a solid-color image equal to the color of that color-stop.

If the distance between the first and last color-stops is non-zero, but is small enough that the implementation knows that the physical resolution of the output device is insufficient to faithfully render the gradient, the implementation must find the average color of the gradient and render the gradient as a solid-color image equal to the average color.

If the distance between the first and last color-stops is zero (or rounds to zero due to implementation limitations), the implementation must find the average color of a gradient with the same number and color of color-stops, but with the first and last color-stop an arbitrary non-zero distance apart, and the remaining color-stops equally spaced between them. Then it must render the gradient as a solid-color image equal to that average color.

If the width of the ending shape of a repeating radial gradient is non-zero and the height is zero, or is close enough to zero that the implementation knows that the physical resolution of the output device is insufficient to faithfully render the gradient, the implementation must find the average color of the gradient and render the gradient as a solid-color image equal to the average color.

Note: The Degenerate Radial Gradients section describes how the ending shape is adjusted when its width is zero.

To find the average color of a gradient, run these steps:

  1. Define list as an initially-empty list of premultiplied RGBA colors, and total-length as the distance between first and last color stops.

  2. For each adjacent pair of color-stops, define weight as half the distance between the two color-stops, divided by total-length. Add two entries to list, the first obtained by representing the color of the first color-stop in premultiplied sRGBA and scaling all of the components by weight, and the second obtained in the same way with the second color-stop.

  3. Sum the entries of list component-wise to produce the average color, and return it.

Note: As usual, implementations may use whatever algorithm they wish, so long as it produces the same result as the above.

For example, the following gradient is rendered as a solid light-purple image (equal to rgb(75%,50%,75%)):
repeating-linear-gradient(red 0px, white 0px, blue 0px);

The following gradient would render the same as the previous under normal circumstances (because desktop monitors can’t faithfully render color-stops 1/10th of a pixel apart), but would render as a normal repeating gradient if, for example, the author applied "zoom:100;" to the element on which the gradient appears:

repeating-linear-gradient(red 0px, white .1px, blue .2px);

3.4. Gradient Color-Stops

<color-stop-list> = <color-stop>{2,}
<color-stop> = <color> <length-percentage>?

The colors in gradients are specified using color stops. A color stop is a combination of a color and a position. (Depending on the type of gradient, that position can be a length, angle, or percentage.) While every color stop conceptually has a position, the position can be omitted in the syntax. (It gets automatically filled in by the user agent; see below for details.)

Color stops are organized into a color stop list, which is a list of one or more color stops.

Color stops are placed on a gradient line, which defines the colors at every point of a gradient. The gradient function defines the shape and length of the gradient line, along with its starting point and ending point.

Color stops must be specified in order. Percentages refer to the length of the gradient line between the starting point and ending point, with 0% being at the starting point and 100% being at the ending point. Lengths are measured from the starting point in the direction of the ending point along the gradient line. Angles are measured with 0deg pointing up, and positive angles corresponding to clockwise rotations from there.

Color stops are usually placed between the starting point and ending point, but that’s not required; the gradient line extends infinitely in both directions, and a color stop can be placed at any position on the gradient line.

The position of a color stop can be omitted. This causes the color stop to position itself automatically between the two surrounding stops. If multiple stops in a row lack a position, they space themselves out equally.

The following steps must be applied in order to process the list of color stops. After applying these rules, all color stops will have a definite position and color and they will be in ascending order:

  1. If the first color stop does not have a position, set its position to 0%. If the last color stop does not have a position, set its position to 100%.

  2. If a color stop has a position that is less than the specified position of any color stop before it in the list, set its position to be equal to the largest specified position of any color stop before it.

  3. If any color stop still does not have a position, then, for each run of adjacent color stops without positions, set their positions so that they are evenly spaced between the preceding and following color stops with positions.

This requires us to wait until after layout to do fix-up, because implied-position stops (set by step 3) may depend on stops that need layout information to place, and which may be corrected by step 2. Swapping steps 2 and 3 would let us interpolate color stops purely at computed-value time, which is a nice plus, at the cost of changing behavior from level 3 for some edge cases that triggered fixup. Make sure this is handled well in the serialization rules.

At each color stop position, the line is the color of the color stop. Between two color stops, the line’s color is interpolated between the colors of the two color stops, with the interpolation taking place in premultiplied RGBA space.

Before the first color stop, the line is the color of the first color stop. After the last color stop, the line is the color of the last color stop.

If multiple color stops have the same position, they produce an infinitesimal transition from the one specified first in the rule to the one specified last. In effect, the color suddenly changes at that position rather than smoothly transitioning.

Below are several pairs of gradients. The latter of each pair is a manually "fixed-up" version of the former, obtained by applying the above rules. For each pair, both gradients will render identically. The numbers in each arrow specify which fixup steps are invoked in the transformation.
1. linear-gradient(red, white 20%, blue)
   =1=>
   linear-gradient(red 0%, white 20%, blue 100%)

2. linear-gradient(red 40%, white, black, blue)
   =13=>
   linear-gradient(red 40%, white 60%, black 80%, blue 100%)

3. linear-gradient(red -50%, white, blue)
   =13=>
   linear-gradient(red -50%, white 25%, blue 100%)

4. linear-gradient(red -50px, white, blue)
   =13=>
   linear-gradient(red -50px, white calc(-25px + 50%), blue 100%)

5. linear-gradient(red 20px, white 0px, blue 40px)
   =2=>
   linear-gradient(red 20px, white 20px, blue 40px)

6. linear-gradient(red, white -50%, black 150%, blue)
   =12=>
   linear-gradient(red 0%, white 0%, black 150%, blue 150%)

7. linear-gradient(red 80px, white 0px, black, blue 100px)
   =23=>
   linear-gradient(red 80px, white 80px, black 90px, blue 100px)
The following example illustrates the difference between a gradient transitioning in pre-multiplied sRGBA and one transitioning (incorrectly) in non-premultiplied. In both of these example, the gradient is drawn over a white background. Both gradients could be written with the following value:
linear-gradient(90deg, red, transparent, blue)

In premultiplied space, transitions to or from "transparent" always look nice:

(Image requires SVG)

On the other hand, if a gradient were to incorrectly transition in non-premultiplied space, the colors near "transparent" would noticeably darken to a grayish color, because "transparent" is actually a shorthand for rgba(0,0,0,0), or transparent black:

(Image requires SVG)

Note: It is recommended that authors not mix different types of units, such as px, em, or %, in a single rule, as this can cause a color stop to unintentionally try to move before an earlier one. For example, the rule background-image: linear-gradient(yellow 100px, blue 50%) wouldn’t require any fix-up as long as the background area is at least 200px tall. If it was 150px tall, however, the blue color stop’s position would be equivalent to "75px", which precedes the yellow color stop, and would be corrected to a position of 100px.

Note: The definition and implications of "premultiplied" color spaces are given elsewhere in the technical literature, but a quick primer is given here to illuminate the process. Given a color expressed as an rgba() 4-tuple, one can convert this to a premultiplied representation by multiplying the red, green, and blue components by the alpha component. For example, a partially-transparent blue may be given as rgba(0,0,255,.5), which would then be expressed as [0, 0, 127.5, .5] in its premultiplied representation. Interpolating colors using the premultiplied representations rather than the plain rgba representations tends to produce more attractive transitions, particularly when transitioning from a fully opaque color to fully transparent. Note that transitions where either the transparency or the color are held constant (for example, transitioning between rgba(255,0,0,100%) and rgba(0,0,255,100%), or rgba(255,0,0,100%) and rgba(255,0,0,0%)) have identical results whether the color interpolation is done in premultiplied or non-premultiplied color-space. Differences only arise when both the color and transparency differ between the two endpoints.

4. Sizing Images and Objects in CSS

Images used in CSS may come from a number of sources: from binary image formats (such as gif, jpeg, etc), dedicated markup formats (such as SVG), and CSS-specific formats (such as the linear-gradient() value type defined in this specification). As well, a document may contain many other types of objects, such as video, plugins, or nested documents. These images and objects (just objects hereafter) may offer many types of sizing information to CSS, or none at all. This section defines generically the size negotiation model between the object and the CSS layout algorithms.

4.1. Object-Sizing Terminology

In order to define this handling, we define a few terms, to make it easier to refer to various concepts:

intrinsic dimensions
The term intrinsic dimensions refers to the set of the intrinsic height, intrinsic width, and intrinsic aspect ratio (the ratio between the width and height), each of which may or may not exist for a given object. These intrinsic dimensions represent a preferred or natural size of the object itself; that is, they are not a function of the context in which the object is used. CSS does not define how the intrinsic dimensions are found in general.

Raster images are an example of an object with all three intrinsic dimensions. SVG images designed to scale might have only an intrinsic aspect ratio; SVG images can also be created with only an intrinsic width or height. CSS gradients, defined in this specification, are an example of an object with no intrinsic dimensions at all. Another example of this is embedded documents, such as the <iframe> element in HTML. An object cannot have only two intrinsic dimensions, as any two automatically define the third.

If an object (such as an icon) has multiple sizes, then the largest size (by area) is taken as its intrinsic size. If it has multiple aspect ratios at that size, or has multiple aspect ratios and no size, then the aspect ratio closest to the aspect ratio of the default object size is used. Determine this by seeing which aspect ratio produces the largest area when fitting it within the default object size using a contain constraint fit; if multiple sizes tie for the largest area, the wider size is chosen as its intrinsic size.

specified size
The specified size of an object is given by CSS, such as through the width and height or background-size properties. The specified size can be a definite width and height, a set of constraints, or a combination thereof.
concrete object size
The concrete object size is the result of combining an object’s intrinsic dimensions and specified size with the default object size of the context it’s used in, producing a rectangle with a definite width and height.
default object size
The default object size is a rectangle with a definite height and width used to determine the concrete object size when both the intrinsic dimensions and specified size are missing dimensions.

4.2. CSS⇋Object Negotiation

Objects in CSS are sized and rendered by the object size negotiation algorithm as follows:

  1. When an image or object is specified in a document, such as through a url() value in a background-image property or a src attribute on an <img> element, CSS queries the object for its intrinsic dimensions.

  2. Using the intrinsic dimensions, the specified size, and the default object size for the context the image or object is used in, CSS then computes a concrete object size. (See the following section.) This defines the size and position of the region the object will render in.

  3. CSS asks the object to render itself at the concrete object size. CSS does not define how objects render when the concrete object size is different from the object’s intrinsic dimensions. The object may adjust itself to match the concrete object size in some way, or even render itself larger or smaller than the concrete object size to satisfy sizing constraints of its own.

  4. Unless otherwise specified by CSS, the object is then clipped to the concrete object size.

4.3. Concrete Object Size Resolution

Currently the rules for sizing objects are described in each context that such objects are used. This section defines some common sizing constraints and how to resolve them so that future specs can refer to them instead of redefining size resolution in each instance.

4.3.1. Default Sizing Algorithm

The default sizing algorithm is a set of rules commonly used to find an object’s concrete object size. It resolves the simultaneous constraints presented by the object’s intrinsic dimensions and either an unconstrained specified size or one consisting of only a definite width and/or height.

Some object sizing rules (such as those for list-style-image) correspond exactly to the default sizing algorithm. Others (such as those for border-image) invoke the default sizing algorithm but also apply additional sizing rules before arriving at a final concrete object size.

The default sizing algorithm is defined as follows:

4.3.2. Cover and Contain Constraint Sizing

Two other common specified sizes are the contain constraint and the cover constraint, both of which are resolved against a specified constraint rectangle using the object’s intrinsic aspect ratio:

In both cases, if the object doesn’t have an intrinsic aspect ratio, the concrete object size is the specified constraint rectangle.

4.4. Examples of CSS Object Sizing

The following examples show how the CSS 2.1 and CSS3 Backgrounds & Borders sizing algorithms correspond to concepts defined in this specification.
background-image
The rules for calculating the concrete object size of a background are defined in CSS2.1§14.2.1 and CSS3BG§3.9. CSS2.1 uses the default sizing algorithm with no specified size and the background positioning area as the default object size. [CSS21] In CSS3, background-size property can give a sizing constraint, invoking either the default sizing algorithm or one of the contain or cover constraints. The concrete object size is further adjusted in later steps if background-repeat has a round value. [CSS3BG]
list-style-image
The rules for calculating the concrete object size of a list-style image are defined in CSS2.1§12.5.1. They use the default sizing algorithm with no specified size and a default object size of 1em square.
border-image
Border images are sized twice: first the entire image is sized to determine the slice points, then the slices are sized to decorate the border. The first sizing operation is defined in CSS3BG§6.2 and uses the default sizing algorithm with no specified size, and the border image area as the default object size. The second operation is defined in CSS3BG§6.2: the default sizing algorithm is used to determine an initial size for each slice with the corresponding border image area part as the default object size. By default the specified size matches this default object size; however the border-image-repeat property can drop the specified size in one or more directions and may also apply an additional rounding step. [CSS3BG]
cursor
The rules for calculating the concrete object size of a cursor are defined in CSS2.1 § 18.1: Cursors. The default object size is a UA-defined size that should be based on the size of a typical cursor on the UA’s operating system. [CSS21]
content
Objects inserted via the CSS2.1 content property are anonymous replaced elements, and are sized the same way. [CSS21] Note that such anonymous elements have all their non-inherited properties (including width, height, etc.) set to their initial values.
replaced elements
CSS 2.1 defines the sizing of replaced elements (including those inserted as generated content via content) in sections 10.3.2, 10.4, 10.6.2, and 10.7. [CSS21] The object-fit property defined below defines how the concrete object size corresponds to the element’s used width and height; by default they coincide.

4.5. Sizing Objects: the object-fit property

Name: object-fit
Value: fill | contain | cover | none | scale-down
Initial: fill
Applies to: replaced elements
Inherited: no
Percentages: n/a
Media: visual
Computed value: specified value
Canonical order: per grammar
Animatable: no

The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

fill
The replaced content is sized to fill the element’s content box: the object’s concrete object size is the element’s used width and height.
contain
The replaced content is sized to maintain its aspect ratio while fitting within the element’s content box: its concrete object size is resolved as a contain constraint against the element’s used width and height.
cover
The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box: its concrete object size is resolved as a cover constraint against the element’s used width and height.
none
The replaced content is not resized to fit inside the element’s content box: determine the object’s concrete object size using the default sizing algorithm with no specified size, and a default object size equal to the replaced element’s used width and height.
scale-down
Size the content as if none or contain were specified, whichever would result in a smaller concrete object size.

Note: Both none and contain respect the content’s intrinsic aspect ratio, so the concept of "smaller" is well-defined.

If the content does not completely fill the replaced element’s content box, the unfilled space shows the replaced element’s background. Since replaced elements always clip their contents to the content box, the content will never overflow. See the object-position property for positioning the object with respect to the content box.

An example showing how four of the values of object-fit cause the replaced element (blue figure) to be scaled to fit its height/width box (shown with a green background), using the initial value for object-position. The fifth value, scale-down, in this case looks identical to contain.

Note: The object-fit property has similar semantics to the fit attribute in [SMIL10] and the <meetOrSlice> parameter on the preserveAspectRatio attribute in [SVG11].

Note: Per the object size negotiation algorithm, the concrete object size (or, in this case, the size of the content) does not directly scale the object itself - it is merely passed to the object as information about the size of the visible canvas. How to then draw into that size is up to the image format. In particular, raster images always scale to the given size, while SVG uses the given size as the size of the "SVG Viewport" (a term defined by SVG) and then uses the values of several attributes on the root <svg> element to determine how to draw itself.

4.6. Positioning Objects: the object-position property

Name: object-position
Value: <position>
Initial: 50% 50%
Applies to: replaced elements
Inherited: no
Percentages: refer to width and height of element itself
Media: visual
Computed value: specified value
Canonical order: the horizontal component of the <position>, followed by the vertical component
Animatable: yes

The object-position property determines the alignment of the replaced element inside its box. The <position> value type (which is also used for background-position) is defined in [css-values-3], and is resolved using the concrete object size as the object area and the content box as the positioning area.

Note: Areas of the box not covered by the replaced element will show the element’s background.

5. Image Processing

5.1. Overriding Image Resolutions: the image-resolution property

The image resolution is defined as the number of image pixels per unit length, e.g., pixels per inch. Some image formats can record information about the resolution of images. This information can be helpful when determining the actual size of the image in the formatting process. However, the information can also be wrong, in which case it should be ignored. By default, CSS assumes a resolution of one image pixel per CSS px unit; however, the image-resolution property allows using some other resolution.

Name: image-resolution
Value: [ from-image || <resolution> ] && snap?
Initial: 1dppx
Applies to: all elements
Inherited: yes
Percentages: n/a
Media: visual
Computed value: as specified, except with <resolution> possibly altered by computed for snap (see below)
Canonical order: per grammar
Animatable: no

The image-set() notation can alter the intrinsic resolution of an image, which ideally would be automatically honored without having to set this property. How should we best address this? Change the initial value to auto, meaning "1dppx, unless CSS says otherwise"? Say that image-resolution has no effect on images whose resolution was set by something else in CSS? Or somehow wordsmithing image-set() in some way such that it always produces 1dppx images somehow?

The image-resolution property specifies the intrinsic resolution of all raster images used in or on the element. It affects both content images (e.g. replaced elements and generated content) and decorative images (such as background-image). The intrinsic resolution of an image is used to determine the image’s intrinsic dimensions. Values have the following meanings:

<resolution>
Specifies the intrinsic resolution explicitly. A "dot" in this case corresponds to a single image pixel.
from-image
The image’s intrinsic resolution is taken as that specified by the image format. If the image does not specify its own resolution, the explicitly specified resolution is used (if given), else it defaults to 1dppx.
snap
If the "snap" keyword is provided, the computed <resolution> (if any) is the specified resolution rounded to the nearest value that would map one image pixel to an integer number of device pixels. If the resolution is taken from the image, then the used intrinsic resolution is the image’s native resolution similarly adjusted.

As vector formats such as SVG do not have an intrinsic resolution, this property has no effect on vector images.

Printers tend to have substantially higher resolution than computer monitors; due to this, an image that looks fine on the screen may look pixellated when printed out. The image-resolution property can be used to embed a high-resolution image into the document and maintain an appropriate size, ensuring attractive display both on screen and on paper:
img.high-res {
  image-resolution: 300dpi;
}

With this set, an image meant to be 5 inches wide at 300dpi will actually display as 5in wide; without this set, the image would display as approximately 15.6in wide since the image is 15000 image pixels across, and by default CSS displays 96 image pixels per inch.

Some image formats can encode the image resolution into the image data. This rule specifies that the UA should use the image resolution found in the image itself, falling back to 1 image pixel per CSS px unit.
img { image-resolution: from-image }

These rules both specify that the UA should use the image resolution found in the image itself, but if the image has no resolution, the resolution is set to 300dpi instead of the default 1dppx.

img { image-resolution: from-image 300dpi }
img { image-resolution: 300dpi from-image }
Using this rule, the image resolution is set to 300dpi. (The resolution in the image, if any, is ignored.)
img { image-resolution: 300dpi }

This rule, on the other hand, if used when the screen’s resolution is 96dpi, would instead render the image at 288dpi (so that 3 image pixels map to 1 device pixel):

img { image-resolution: 300dpi snap; }

The snap keyword can also be used when the resolution is taken from the image:

img { image-resolution: snap from-image; }

An image declaring itself as 300dpi will, in the situation above, display at 288dpi (3 image pixels per device pixel) whereas an image declaring 72dpi will render at 96dpi (1 image pixel per device pixel).

5.2. Orienting an Image on the Page: the image-orientation property

This property is likely going to be deprecated and its functionality moved to HTML. At minimum, it will likely lose all but its initial value and from-image.

If a picture is taken with a camera turned on its side, or a document isn’t positioned correctly within a scanner, the resultant image may be "sideways" or even upside-down. The image-orientation property provides a way to apply an "out-of-band" rotation to image source data to correctly orient an image.

Note: This property is not intended to specify layout transformations such as arbitrary rotation or flipping the image in the horizontal or vertical direction. (See [CSS3-2D-TRANSFORMS] for a feature designed to do that.) It is also not needed to correctly orient an image when printing in landscape versus portrait orientation, as that rotation is done as part of layout. (See [CSS3PAGE].) It should only be used to correct incorrectly-oriented images.

Name: image-orientation
Value: from-image | <angle> | [ <angle>? flip ]
Initial: 0deg
Applies to: all elements
Inherited: yes
Percentages: n/a
Media: visual
Computed value: an <angle>, rounded and normalized (see text), plus optionally a flip keyword
Canonical order: per grammar
Animatable: no

This property specifies an orthogonal rotation to be applied to an image before it is laid out. It applies only to content images (e.g. replaced elements and generated content), not decorative images (such as background-image). CSS layout processing applies to the image after rotation. This implies, for example:

Values have the following meanings:

from-image
If the image has an orientation specified in its metadata, such as EXIF, this value computes to the angle that the metadata specifies is necessary to correctly orient the image. If necessary, this angle is then rounded and normalized as described above for an <angle> value. If there is no orientation specified in its metadata, this value computes to 0deg.
<angle>
Positive values cause the image to be rotated to the right (in a clockwise direction), while negative values cause a rotation to the left. The computed value of the property is calculated by rounding the specified angle to the nearest quarter-turn (90deg, 100grad, .25turn, etc.), rounding away from 0 (that is, 45deg is rounded to 90deg, while -45deg is rounded to -90deg), then moduloing the value by 1 turn (360deg, 400grad, etc.).
<angle>? flip
Identical to the plain <angle> case, except that after rotation the image is flipped horizontally. If the <angle> is omitted, it defaults to 0deg.

Note: This value is only necessary to represent all 8 possible EXIF orientations that from-image can produce.

The image-orientation property must be applied before any other transformations, such as being specified in the image() function with an opposite directionality to its context, or using CSS Transforms.

The following example rotates the image 90 degrees clockwise:
img.ninety     { image-orientation: 90deg }
...
<img class="ninety" src=...>

The same effect could be achieved with, for example, an angle of -270deg or 450deg.

5.3. Determing How To Scale an Image: the image-rendering property

Name: image-rendering
Value: auto | crisp-edges | pixelated
Initial: auto
Applies to: all elements
Inherited: yes
Percentages: n/a
Media: visual
Computed value: specified value
Canonical order: per grammar
Animatable: no

The image-rendering property provides a hint to the user-agent about what aspects of an image are most important to preserve when the image is scaled, to aid the user-agent in the choice of an appropriate scaling algorithm. When specified on an element, it applies to all images given in properties for the element, such as background images, list-style images, or the content of replaced elements when they represent an image that must be scaled. The values of the image-rendering property are interpreted as follows:

auto
The image should be scaled with an algorithm that maximizes the appearance of the image. In particular, scaling algorithms that "smooth" colors are acceptable, such as bilinear interpolation. This is intended for images such as photos.
high-quality
Identical to auto, but with a preference for higher-quality scaling. If system resources are constrained, images with high-quality should be prioritized over those with auto, when considering which images to degrade the quality of and to what degree.
This value does not prevent the image quality from being degraded when the system resources are constrained. It merely expresses a preference that these images should receive extra scaling resources relative to the auto images. If all images on the page have high-quality applied, it’s equivalent to all of them having auto applied—they’re all treated the same.

To get the most value out of high-quality, only apply it to the most important images on the page.

The name of this value is currently being discussed.

crisp-edges
The image must be scaled with an algorithm that preserves contrast and edges in the image, and which does not smooth colors or introduce blur to the image in the process. This is intended for images such as pixel art.
pixelated
The image must be scaled with the "nearest neighbor" or similar algorithm, to preserve a "pixelated" look as the image changes in size.

This property does not dictate any particular scaling algorithm to be used. For example, with image-rendering: auto, a user agent might scale images with bilinear interpolation by default, switch to nearest-neighbor interpolation in high-load situations, and switch to a high-quality scaling algorithm like Lanczos interpolation for static images that aren’t moving or changing. Similarly, with 'image-rendering: crisp-edges', a user agent might scale images with nearest-neighbor interpolation by default, and switch to EPX interpolation in low-load situations.

For example, given the following small image:
A small pixel-art image.

Scaling it up 3x might look like the following, depending on the value of image-rendering:

The image scaled with auto
The image scaled with pixelated
The image scaled with crisp-edges.
(Or it might look like pixelated, or as another type of pixel-scaling algorithm, depending on the browser.)

This property previously accepted the values optimizeSpeed and optimizeQuality. These are now deprecated; a user agent must accept them as valid values but must treat them as having the same behavior as pixelated and auto respectively, and authors must not use them.

6. Interpolation

This section describes how to interpolate between new value types defined in this specification, for use with modules such as CSS Transitions and CSS Animations.

If an algorithm below simply states that two values should be "interpolated" or "transitioned" without further details, then the value should be interpolated as described by the Transitions spec. Otherwise, the algorithm may reference a variable "t" in its detailed description of the interpolation. This is a number which starts at 0% and goes to 100%, and is set to a value that represents the progress through the transition, based on the duration of the transition, the elapsed time, and the timing function in use. For example, with a linear timing function and a 1s duration, after .3s t is equal to 30%.

6.1. Interpolating <image>

All images can be interpolated, though some special types of images (like some gradients) have their own special interpolation rules. In general terms, images are interpolated by scaling them to the size of the start image and cross-fading the two while they transition to the size of the end image.

In specific terms, at each point in the interpolation the image is equal to cross-fade( (100% - t) start image, end image).

Special-case interpolating to/from no image, like "background-image: url(foo);" to "background-image: none;".

6.2. Interpolating cross-fade()

If both the starting and ending images are cross-fade()s which differ only by by their <percentage>, they must be interpolated by interpolating their <percentage>. Otherwise, they must be interpolated as generic <image>s.

6.3. Interpolating <gradient>

This section needs review and improvement. In particular, I believe the handling of linear-gradient() is incomplete - I think we want to specifically interpolate the "length" of the gradient line (the distance between 0% and 100%) between the starting and ending positions explicitly, so it doesn’t grow and then shrink over a single animation.

Gradient images can be interpolated directly in CSS transitions and animations, smoothly animating from one gradient to another. There are only a few restrictions on what gradients are allowed to be interpolated:

  1. Both the starting and ending gradient must be expressed with the same function. (For example, you can transition from a linear-gradient() to a linear-gradient(), but not from a linear-gradient() to a radial-gradient() or a repeating-linear-gradient().)

  2. Both the starting and ending gradient must have the same number of <color-stop>s. Note that one can pad a gradient with additional <color-stop>s placed atop each other, if necessary to make two gradients have the same number of <color-stop>s.)

    For this purpose, all repeating gradients are considered to have "infinite" color stops, and thus all repeating gradients match in this respect.

If the two gradients satisfy both of those constraints, they must be interpolated as described below. If not, they must be interpolated as a generic <image>.

  1. Convert both the start and end gradients to their explicit forms:

    For linear gradients:

    • If the direction is specified as an <angle>, it is already in its explicit form.

    • Otherwise, change its direction to an <angle> in [0deg,360deg) that would produce an equivalent rendering.

      If both the start and end gradients had their direction specified with keywords, and the absolute difference between the angles their directions mapped to is greater than 180deg, add 360deg to the direction of the gradient with the smaller angle. This ensures that a transition from, for example, "to left" (270deg) to "to top" (0deg) rotates the gradient a quarter-turn clockwise, as expected, rather than rotating three-quarters of a turn counter-clockwise.

    For radial gradients:

    • If the size is specified as two <length>s or <percentage>s, it is already in its explicit form.

    • Otherwise, the size must be changed to a pair of <length>s that would produce an equivalent ending-shape. If the <ending-shape> was specified as circle, change it to ellipse.

  2. Interpolate each component and color-stop of the gradients independently. For linear gradients, the only component is the angle. For radial gradients, the components are the horizontal and vertical position of the center and the horizontal and vertical axis lengths.

  3. To interpolate a color-stop, first match each color-stop in the start gradient to the corresponding color-stop at the same index in the end gradient. For repeating gradients, the first specified color-stop in the start and end gradients are considered to be at the same index, and all other color-stops following and preceding are indexed appropriately, repeating and shifting each gradient’s list of color-stops as needed. Then, for each pair of color-stops, interpolate the position and color independently.

7. Serialization

This section describes the serialization of all new properties and value types introduced in this specification, for the purpose of interfacing with the CSS Object Model [CSSOM].

To serialize any function defined in this module, serialize it per its individual grammar, in the order its grammar is written in, omitting components when possible without changing the meaning, joining space-separated tokens with a single space, and following each serialized comma with a single space.

For cross-fade(), always serialize the <percentage>.

For example, a gradient specified as:
Linear-Gradient( to bottom, red 0%,yellow,black 100px)

must serialize as:

linear-gradient(red, yellow, black 100px)

8. Privacy and Security Considerations

This specification allows rendering of cross-origin images by default, which exposes some information of those images programmatically—specifically, the intrinsic sizes and resolution of those images.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Requirements for Responsible Implementation of CSS

The following sections define several conformance requirements for implementing CSS responsibly, in a way that promotes interoperability in the present and future.

Partial Implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported property values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

Implementations of CR-level Features

Once a specification reaches the Candidate Recommendation stage, implementers should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec, and should avoid exposing a prefixed variant of that feature.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-BACKGROUNDS-3]
CSS Backgrounds and Borders Module Level 3 URL: https://drafts.csswg.org/css-backgrounds-3/
[CSS-COLOR-3]
CSS Color Module Level 3 URL: https://drafts.csswg.org/css-color-3/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley. CSS Color Module Level 4. URL: https://drafts.csswg.org/css-color/
[CSS-FLEXBOX-1]
Tab Atkins Jr.; Elika Etemad; Rossen Atanassov. CSS Flexible Box Layout Module Level 1. URL: https://drafts.csswg.org/css-flexbox/
[CSS-GCPM-3]
Dave Cramer. CSS Generated Content for Paged Media Module. URL: http://dev.w3.org/csswg/css-gcpm/
[CSS-LISTS-3]
Tab Atkins Jr.. CSS Lists and Counters Module Level 3. URL: http://dev.w3.org/csswg/css3-lists/
[CSS-VALUES-3]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. URL: https://drafts.csswg.org/css-values/
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. REC. URL: https://www.w3.org/TR/CSS2
[CSS22]
Bert Bos. Cascading Style Sheets Level 2 Revision 2 (CSS 2.2) Specification. URL: http://dev.w3.org/csswg/css2/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[MEDIA-FRAGS]
Raphaël Troncy; et al. Media Fragments URI 1.0 (basic). 25 September 2012. REC. URL: https://www.w3.org/TR/media-frags/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119

Informative References

[CSS-CONTENT-3]
Elika Etemad; Dave Cramer. CSS Generated Content Module Level 3. URL: https://drafts.csswg.org/css-content/
[CSS3-2D-TRANSFORMS]
Simon Fraser; et al. CSS 2D Transforms. 15 December 2011. WD. URL: https://www.w3.org/TR/css3-2d-transforms/
[CSS3BG]
Bert Bos; Elika Etemad; Brad Kemper. CSS Backgrounds and Borders Module Level 3. URL: http://dev.w3.org/csswg/css3-background/
[CSS3PAGE]
Melinda Grant; et al. CSS Paged Media Module Level 3. 14 March 2013. WD. URL: https://www.w3.org/TR/css3-page/
[CSSOM]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). URL: https://drafts.csswg.org/cssom/
[PAINT-3]
CSS Fill and Stroke Module Level 3 URL: https://drafts.fxtf.org/paint/
[PORTERDUFF]
Thomas Porter; Tom Duff. Compositing digital images. July 1984.
[SMIL10]
Philipp Hoschka. Synchronized Multimedia Integration Language (SMIL) 1.0 Specification. URL: https://www.w3.org/TR/1998/REC-smil-19980615
[SVG11]
Erik Dahlström; et al. Scalable Vector Graphics (SVG) 1.1 (Second Edition). 16 August 2011. REC. URL: https://www.w3.org/TR/SVG11/

Property Index

Name Value Initial Applies to Inh. %ages Media Ani­mat­able Canonical order Com­puted value
object-fit fill | contain | cover | none | scale-down fill replaced elements no n/a visual no per grammar specified value
object-position <position> 50% 50% replaced elements no refer to width and height of element itself visual yes the horizontal component of the <position>, followed by the vertical component specified value
image-resolution [ from-image || <resolution> ] && snap? 1dppx all elements yes n/a visual no per grammar as specified, except with <resolution> possibly altered by computed for snap (see below)
image-orientation from-image | <angle> | [ <angle>? flip ] 0deg all elements yes n/a visual no per grammar an <angle>, rounded and normalized (see text), plus optionally a flip keyword
image-rendering auto | crisp-edges | pixelated auto all elements yes n/a visual no per grammar specified value

Issues Index

This solution assumes that resolution is a proxy for filesize, and therefore doesn’t appropriately handle multi-resolution sets of vector images, or mixing vector images with raster ones (e.g. for icons). For example, use a vector for high-res, pixel-optimized bitmap for low-res, and same vector again for low-bandwidth (because it’s much smaller, even though it’s higher resolution).
We should add "w" and "h" dimensions as a possibility, and a "format()" function, to match the functionality of HTML’s picture.
Is this restriction needed?
We should add the ability to move the focus of the gradient, as in the original -webkit-gradient() function. See proposal in http://lists.w3.org/Archives/Public/www-style/2011Nov/0210.html for "from <position>" and "from offset <offset>".
This requires us to wait until after layout to do fix-up, because implied-position stops (set by step 3) may depend on stops that need layout information to place, and which may be corrected by step 2. Swapping steps 2 and 3 would let us interpolate color stops purely at computed-value time, which is a nice plus, at the cost of changing behavior from level 3 for some edge cases that triggered fixup. Make sure this is handled well in the serialization rules.
The image-set() notation can alter the intrinsic resolution of an image, which ideally would be automatically honored without having to set this property. How should we best address this? Change the initial value to auto, meaning "1dppx, unless CSS says otherwise"? Say that image-resolution has no effect on images whose resolution was set by something else in CSS? Or somehow wordsmithing image-set() in some way such that it always produces 1dppx images somehow?
This property is likely going to be deprecated and its functionality moved to HTML. At minimum, it will likely lose all but its initial value and from-image.
The name of this value is currently being discussed.
Special-case interpolating to/from no image, like "background-image: url(foo);" to "background-image: none;".
This section needs review and improvement. In particular, I believe the handling of linear-gradient() is incomplete - I think we want to specifically interpolate the "length" of the gradient line (the distance between 0% and 100%) between the starting and ending positions explicitly, so it doesn’t grow and then shrink over a single animation.