aboutsummaryrefslogtreecommitdiff
path: root/files/es/web/css/linear-gradient()/index.html
blob: 4a68a3b365db19a7175d0ba7c7580055c175726d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
---
title: linear-gradient
slug: Web/CSS/linear-gradient()
tags:
  - CSS
  - Función CSS
  - Imágenes CSS
  - Plantilla
  - Referencia
  - Web
  - graficos
translation_of: Web/CSS/linear-gradient()
---
<p>{{ CSSRef() }}</p>

<h2 id="Resumen">Resumen</h2>

<p>La función CSS <code>linear-gradient()</code> crea una imágen la cual representa un degradado lineal de colores. El resultado es un objeto CSS de tipo {{cssxref("&lt;gradient&gt;")}}, que es una forma especial de {{cssxref("&lt;image&gt;")}}.</p>

<p>{{EmbedInteractiveExample("pages/css/function-linear-gradient.html")}}</p>

<p>Cómo cualquier otro degradado, un degradado lineal no tiene<a href="/en/CSS/image#no_intrinsic"> dimensiones intrínsecas</a>; es decir,  no tiene un tamaño natural o predefinido, ni una relación de aspecto. Su tamaño concreto se ajustará al del elemento al cual se le aplica.</p>

<p>Los gradientes lineales están definidos por un eje, la <em>línea gradiente</em>, donde cada punto representa el inicio de un color diferente. Las líneas perpendiculares a la <em>línea gradiente</em> tienen un único color, para cada punto de la <em>línea gradiente</em>.</p>

<p><img alt="linear-gradient.png" src="/files/3537/linear-gradient.png" style="float: left; height: 383px; width: 309px;"></p>

<p>La línea gradiente está definida por el centro de la caja que contiene la imagen gradiente y por un ángulo. El color del gradiente está definido por diferentes puntos; el punto de inicio, el punto de fin y, en el medio, puntos opcionales de cambio de color.</p>

<p>El punto de inicio es el punto en la línea gradiente donde empieza el color. Está definido por la intersección entre la línea gradiente y su perpendicular, pasando por la esquina del contenedor en el mismo cuadrante.</p>

<p>De forma similar, el punto de fin es el punto de la línea gradiente donde se alcanza el final del color. También está definido por la intersección entre la línea gradiente y la línea perpendicular generada por la esquina más cercana del contenedor, pero es más fácil encontrarla como la simetría del punto de inicio, cuando el punto de reflección coincide con el centro de la caja contenedora.</p>

<p>Estas definiciones algo complejas de los puntos de inicio y fin nos llevan a una propiedad interesante llamda <em>magic corners</em> (esquinas mágicas): La esquina más cercana de los puntos de inicio y fin, tienen el mismo color que su respectivos puntos de inicio y fin.</p>

<p>Se puede especificar más que solamente los colores de los puntos de inicio y fin. Definiendo colores adicionales en los puntos de cambio en la línea gradiente, el desarrollador web puede crear una transición más personalizada entre los colores de inicio y fin, o generar un gradiente de múltiples colores.</p>

<p>La sintaxis de la función linear-gradient no permite la repetición de gradientes, pero usando puntos de cambio de color, se puede generar un efecto similar. Para una repetición de gradientes real, puede usar la propiedad CSS {{ Cssxref("repeating-linear-gradient") }}.</p>

<p>When the position of a color-stop point is implicitly defined, it is placed half-way between the point that precedes it and the one that follows it.  The position can also be explicitly defined by using a {{cssxref("&lt;length&gt;")}} or a {{cssxref("&lt;percentage&gt;")}} CSS data type.</p>

<div class="note">Gradients are defined as CSS <code>&lt;image&gt;</code> data types. Therefore they can be used anywhere in CSS where an image data type is required. But, Gecko currently only supports CSS gradients as values of the {{ Cssxref("background-image") }} property, as well as within the shorthand {{ Cssxref("background") }}.<br>
For this reason, <code>linear-gradient</code> won't work on {{ Cssxref("background-color") }} and other properties requesting {{cssxref("&lt;color&gt;")}}.</div>

<h2 id="Syntax">Syntax</h2>

<pre class="twopartsyntaxbox notranslate">Formal grammar: linear-gradient(  [ <a href="/en-US/CSS/angle" title="angle">&lt;angle&gt;</a> | to &lt;side-or-corner&gt; ,]? &lt;color-stop&gt; [, &lt;color-stop&gt;]+ )
                                  \---------------------------------/ \----------------------------/
                                    Definition of the gradient line         List of color stops

                      where <code>&lt;side-or-corner&gt; = [left | right] || [top | bottom]</code>
                        and <code>&lt;color-stop&gt;     = &lt;color&gt; [ &lt;percentage&gt; | &lt;length&gt; ]?</code>
</pre>

<pre class="notranslate">linear-gradient( 45deg, blue, red );           /* A gradient on 45deg axis starting blue and finishing red */
linear-gradient( to left top, blue, red);      /* A gradient going from the bottom right to the top left starting blue and
                                                  finishing red */

linear-gradient( 0deg, blue, green 40%, red ); /* A gradient going from the bottom to top, starting blue, being green after 40%
                                                  and finishing red */
</pre>

<h3 id="Values">Values</h3>

<dl>
 <dt><code>&lt;side-or-corner&gt;</code></dt>
 <dd>Represents the position of the starting-point of the gradient line. It consists of two keywords: the first one indicates the horizontal side, <code>left</code> or <code>right</code>, and the second one the vertical side, <code>top</code> or <code>bottom</code>. The order is not relevant and each of the keyword is optional.<br>
 The values <code>to top</code>, <code>to bottom</code>, <code>to left</code> and <code>to right</code> are translated into the angles <code>0deg</code>, <code>180deg</code>, <code>270deg</code>, <code>90deg</code> respectively. The others are translated into an angle that let the starting-point to be in the same quadrant than the described corner and so that the line defined by the starting-point and the corner is perpendicular to the gradient line. That way, the color described by the <code>&lt;color-stop&gt;</code> will exactly apply to the corner point. This is sometimes called the "<em>magic corner</em>" property. The end-point of the gradient line is the symmetrical point of the starting-point on the other direction of the center box.</dd>
 <dt><code>&lt;angle&gt;</code></dt>
 <dd>An angle of direction for the gradient. See {{ cssxref("&lt;angle&gt;") }}.</dd>
 <dt><code>&lt;color-stop&gt;</code></dt>
 <dd>This value is comprised of a {{cssxref("&lt;color&gt;")}} value, followed by an optional stop position (either a percentage or a {{cssxref("&lt;length&gt;")}} along the gradient axis).<br>
 Rendering of color-stops in CSS gradients follows the same rules as color-stops in SVG gradients.</dd>
</dl>

<h3 id="History_of_the_syntax">History of the syntax</h3>

<p>The syntax of <code>linear-gradient</code> has evolved since the <a class="external" href="http://www.webkit.org/blog/175/introducing-css-gradients/" title="http://www.webkit.org/blog/175/introducing-css-gradients/">first Apple proposal</a> implemented in 2008:</p>

<pre class="notranslate"><code>-webkit-gradient(&lt;type&gt;, &lt;point&gt; [, &lt;radius&gt;]?, &lt;point&gt; [, &lt;radius&gt;]? [, &lt;stop&gt;]*)</code>
</pre>

<p>In the original syntax, the same function was used to create both linear and radial gradients.  However, the parameters needed in each case were different, resulting in a syntax that varied with the value of the first parameter.  The situation became more complicated if  other types of gradients, like conical gradients, were added, requiring the use of functions and non-standard or inconsistent css value specifications.  No draft was proposed to the W3C.</p>

<p>An alternative syntax was proposed and implemented by Mozilla in 2009.  In this syntax, two CSS functions would be required; one for linear gradients, and the other for radial gradients. However, this syntax never shipped in a released product.  A third syntax was proposed.  This third syntax simplified the syntax for linear gradients to:</p>

<pre class="notranslate">-moz-linear-gradient(<code>[ [ [top | bottom] || [left | right] ],]? &lt;color-stop&gt;[, &lt;color-stop&gt;]+);</code>
</pre>

<p>The new syntax did not require the <code>to()</code>, <code>from()</code>and <code>color-stop()</code> functions, so they were dropped. The order of the <code>top</code>/<code>bottom</code> and <code>left</code>/<code>right</code> keywords was also recognized as unimportant, so Mozilla removed the constraint of having <code>top</code>/<code>bottom</code> defined first. </p>

<p>But the new syntax had still had one drawback: it allowed only vertical and horizontal gradients.  Finally, the syntax below was proposed to the W3C.  Following two more changes to solve the limitation on the direction of gradients, it was added to the CSS Images Values and Content Replacement Level 3 draft in 2011.</p>

<ul>
 <li>The support of an {{ cssxref("&lt;angle&gt;") }} as an origin, allowing gradients of any direction.</li>
 <li>The definition of the magic corner algorithm which eases the work of Web developers by allowing an easy definition of the exact color at the corners.</li>
</ul>

<p>The color interpolation is also defined as happening in the pre-multiplied color space, in order to prevent non esthetic grey to appear when using color with different opacity. This syntax was implemented, prefixed, by both Webkit, without dropping the original one, and Trident (IE 10):</p>

<pre class="notranslate">linear-gradient(<code> [ </code>[ {{cssxref("&lt;angle&gt;")}} | <code>[top | bottom] || [left | right] ],]? &lt;color-stop&gt;[, &lt;color-stop&gt;]+);</code>
</pre>

<p>Unfortunately, the addition of the {{ cssxref("&lt;angle&gt;") }} values to the syntax introduced an incoherence: the angle indicates a destination, but the keywords indicate a starting point.<a class="external" href="http://lists.w3.org/Archives/Public/www-style/2011Jun/0377.html" title="http://lists.w3.org/Archives/Public/www-style/2011Jun/0377.html"># </a>This was fixed by a new syntax where the keyword are directions too, and preceded by the <code>to</code> keyword.</p>

<pre class="notranslate">linear-gradient(<code>[ [ </code>[ {{cssxref("&lt;angle&gt;")}} | to <code>[top | bottom] || [left | right] ],]? &lt;color-stop&gt;[, &lt;color-stop&gt;]+);</code>
</pre>

<p>This should be the final syntax.</p>

<p>A last semantic curiosity still exists between the prefixed variants and the unprefixed proposal. Following the initial Apple proposal, the prefixed variants of the syntax all uses the an {{ cssxref("&lt;angle&gt;") }} defined like polar angles, that is with <code>0deg</code> representing the East. To be coherent with the rest of CSS, the specification defines an angle with <code>0deg</code> representing the North. To prevent sites using prefixed version of the property to get suddenly broken, even when adapting to the otherwise forward-compatible final syntax, they keep the original angle definition (<code>0deg</code> = East<code>)</code>. They will switch to the correct spec when unprefixing the property. Also, as they aren't incompatible, Gecko supports, prefixed, both the syntax with the <code>to</code> keyword and without. Here again, the syntax without the keyword will be dropped when unprefixing.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Gradient_at_a_45_degree_angle">Gradient at a 45 degree angle</h3>

<p>Positions can be specified along the gradient axis with a color for each of them, called "color-stops", and the areas between every color-stop smoothly transition between each other. Any one color in the gradient forms a straight line that is perpendicular to the gradient axis. In the below image, the gradient's axis starts from the top-left corner of the div, and is directed at a 45 degree angle. Two color-stops are specified, red and blue.</p>

<p><img alt="lingradexample.png" class="default internal" src="/files/2843/lingradexample.png" style="height: 329px; width: 453px;"></p>

<h3 id="Gradient_with_multiple_color_stops">Gradient with multiple color stops</h3>

<p>If the first color-stop does not have a <code>&lt;length&gt;</code> or <code>&lt;percentage&gt;</code>, it defaults to 0%. If the last color-stop does not have a <code>&lt;length&gt;</code> or <code>&lt;percentage&gt;</code>, it defaults to 100%. If a color-stop doesn't have a specified position and it isn't the first or last stop, then it is assigned the position that is half way between the previous stop and next stop.</p>

<p>Color-stops must be specified in order. After assigning default values to the first and last stops if necessary, if a color-stop has a specified position that is less than the specified position of any color-stop before it in the list, its position is changed to be equal to the largest specified position of any color-stop before it.</p>

<div>A rainbow made from a gradient</div>

<pre class="notranslate">background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
</pre>

<h3 id="Repeating_a_linear_gradient">Repeating a linear gradient</h3>

<p>The <code>linear-gradient</code> does not allow repeating gradients. By default, the gradient will stretch to fill the element it is defined on. For this functionality, see {{ Cssxref("repeating-linear-gradient") }}.</p>

<h3 id="Using_transparency">Using transparency</h3>

<div>Linear with transparency</div>

<pre class="notranslate">background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0));</pre>

<p>Gradient backgrounds are not affected by {{ Cssxref("background-size") }} if all points and lengths are specified using fixed units (as opposed to percentages or keywords, which are relative to the value of <code>background-size</code>).</p>

<h2 id="Notes">Notes</h2>

<p>If you set the {{ cssxref("background-image") }} property of the {{ HTMLElement("body") }} tag to a <code>linear-gradient</code>, the gradient <a class="external" href="http://richard.milewski.org/archives/1014" title="http://richard.milewski.org/archives/1014">won't fill the browser screen unless </a>you also set the {{ cssxref("min-height") }} property of the document root (e.g. the {{ HTMLElement("html") }} tag) to 100%.</p>

<h2 id="Specifications" name="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{ SpecName('CSS3 Images', '#linear-gradient-type', 'linear-gradient()') }}</td>
   <td>{{ Spec2('CSS3 Images') }}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Firefox (Gecko)</th>
   <th>Chrome</th>
   <th>Internet Explorer</th>
   <th>Opera (Presto)</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support(on {{ cssxref("background") }} and {{ cssxref("background-image") }})</td>
   <td>{{ CompatGeckoDesktop("1.9.2") }}{{ property_prefix("-moz") }}<sup><a href="#bc3">[3]</a></sup><br>
    {{ CompatGeckoDesktop("16") }}</td>
   <td>10.0 (534.16){{ property_prefix("-webkit") }} <sup><a href="#bc2">[2]</a></sup><sup><a href="#bc3">[3]</a></sup></td>
   <td>10.0 <sup><a href="#bc1">[1]</a></sup></td>
   <td>11.10{{ property_prefix("-o") }} <sup><a href="#bc3">[3]</a></sup></td>
   <td>5.1{{ property_prefix("-webkit") }}<sup><a href="#bc2">[2]</a></sup><sup><a href="#bc3">[3]</a></sup></td>
  </tr>
  <tr>
   <td>On any properties that accept {{cssxref("&lt;image&gt;")}}</td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
   <td>{{ CompatUnknown() }}</td>
   <td>{{ CompatUnknown() }}</td>
   <td>{{ CompatVersionUnknown() }}</td>
  </tr>
  <tr>
   <td><a class="external" href="http://www.webkit.org/blog/175/introducing-css-gradients/">Legacy webkit syntax</a>{{ non-standard_inline() }}</td>
   <td>{{ CompatNo() }}</td>
   <td>3{{ property_prefix("-webkit") }} <sup><a href="#bc2">[2]</a></sup></td>
   <td>{{ CompatNo() }}</td>
   <td>{{ CompatNo() }}</td>
   <td>4.0{{ property_prefix("-webkit") }}<sup><a href="#bc2">[2]</a></sup></td>
  </tr>
  <tr>
   <td>Legacy <em>from </em>syntax (without <code>to</code>){{ non-standard_inline() }}</td>
   <td>{{ CompatGeckoDesktop("1.9.2") }}{{ property_prefix("-moz") }} <sup><a href="#bc4">[4]</a></sup></td>
   <td>10.0 (534.16){{ property_prefix("-webkit") }} <sup><a href="#bc2">[2]</a></sup></td>
   <td>10</td>
   <td>11.10{{ property_prefix("-o") }}<sup><a href="#bc4">[4]</a></sup></td>
   <td>5.1{{ property_prefix("-webkit") }}<sup><a href="#bc2%3E">[2]</a></sup></td>
  </tr>
  <tr>
   <td>Standard syntax (using the <code>to</code> keyword)</td>
   <td>16</td>
   <td>26.0 (537.27)</td>
   <td>10</td>
   <td>12.10</td>
   <td>6.1</td>
  </tr>
 </tbody>
</table>

<p><sup><a name="bc1">[1]</a></sup> Internet Explorer 5.5 through 9.0 supports proprietary <a class="external" href="http://msdn.microsoft.com/en-us/library/ms532997(VS.85,loband).aspx"><code>filter: progid:DXImageTransform.Microsoft.Gradient()</code> filter</a>.</p>

<p><sup><a name="bc2">[2]</a></sup> WebKit since 528 supports the legacy <a class="external" href="http://developer.apple.com/safari/library/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Gradients/Gradients.html"><code>-webkit-gradient(linear,…)</code> function</a>. As of WebKit 534.16, it also supports the standard gradient syntax. Unlike in Gecko, in legacy WebKit you cannot specify both a position and angle in <code>-webkit-linear-gradient()</code>. You can achieve the same effect by offsetting the color stops.</p>

<p><sup><a name="bc3">[3]</a></sup> Gecko, Opera &amp; Webkit considers {{ cssxref("&lt;angle&gt;") }} to start to the right, instead of the top. I.e. it considered an angle of <code>0deg</code> as a direction indicator pointing to the right. This is different from the latest specification where an angle of <code>0deg</code> as a direction indicator points to the top.</p>

<p><sup><a name="bc4">[4]</a></sup> Firefox 3.6 and Opera 11.10 implemented, prefixed, an early syntax where the starting corner or side was indicated without the <code>to</code> keyword, and effectively considered as a <em>from</em> position. The <code>to</code> syntax has been added in Firefox 10 and Opera 11.60 , at first without removing the deprecated syntax and translation between the two is trivial:</p>

<pre class="notranslate">linear-gradient(to top left, blue, red);</pre>

<p>is almost the same as:</p>

<pre class="notranslate">-moz-linear-gradient(bottom right, blue, red);</pre>

<p>The legacy syntax, without <code>to</code>, is planned to go away when the prefix is removed.</p>

<h3 id="Cross-browser_gradients">Cross-browser gradients</h3>

<p>Considering all prefixes above, here is a gradient from pink to green, top to bottom.</p>

<pre class="brush: css notranslate">.grad {
  background-color: #F07575; /* fallback color if gradients are not supported */
  background-image: -webkit-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
  background-image:    -moz-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For Firefox (3.6 to 15) */
  background-image:      -o-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For old Opera (11.1 to 12.0) */
  background-image:         linear-gradient(to bottom, hsl(0, 80%, 70%), #bada55); /* Standard syntax; must be last */
}
</pre>

<p>The -moz- prefixed rules are used for compatibility with older versions (Fx 3.6 to Fx 15). The -webkit-prefix is the only one that still needs to be included for Android 4.3-, iOS up to 6.1, and Safari 6. When using a prefix, do not use 'to'.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en/CSS/Using_CSS_gradients" title="en/Using gradients">Using CSS gradients</a>, {{ cssxref("radial-gradient", "radial-gradient()") }}, {{ cssxref("repeating-linear-gradient", "repeating-linear-gradient()") }}, {{ cssxref("repeating-radial-gradient", "repeating-radial-gradient()") }};</li>
 <li>Some properties where it can be used: {{ cssxref("background-image") }}, {{ cssxref("background") }};</li>
 <li><a class="external" href="http://lea.verou.me/css3patterns/" title="http://leaverou.me/css3patterns/">CSS Gradients Patterns Gallery, by Lea Verou</a><span class="external">;</span></li>
 <li><a class="external" href="http://standardista.com/cssgradients" title="http://standardista.com/cssgradients">CSS3 Gradients Library, by Estelle Weyl</a>.</li>
</ul>