filter

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

Resumen

La propiedad CSS filter dota de efectos como el desenfoque o cambio de color en la representación de un elemento antes de que se muestre el elemento. Los filtros se utilizan comúnmente para ajustar la representación de una imagen, un fondo o un border.

Incluido en el estandar CSS son varias funciones que logran efectos predefinidos. También puede hacer referencia a un filtro especificado en SVG con una URL  a un filtro de un elemento SVG.

Nota: Versiones anteriores (4.0 hasta 9.0) del Navegador Internet Explorer de Windows admiten un "filtro" no incluido en el estandar que ha quedado en desuso.

Valor inicialnone
Applies toall elements; In SVG, it applies to container elements excluding the defs element and all graphics elements
Heredableno
Mediavisual
Valor calculadocomo se especifica
Animatableyes
Canonical orderel orden único no-ambigüo definido por la gramática formal

Sintaxis

Aplicando un filtro con las funciones unicas de CSS, usa el siguiente:

filter: <filter-function> [<filter-function>]* | none

Aplicar un filtro desde un referencia de un SVG <filter> elemento, usa el siguiente:

filter: url(svg-url#element-id) 

Ejemplos

Ejemplos del uso de las funciones predefinidas se muestran a continuación. Ver cada función. Ver cada función para un ejemplo específico.

.mydiv { filter: grayscale(50%) }

/* funcion del blanco y negro "grayscale" al 50% y un desenfoque "blur" de 10px */
img {
  filter: grayscale(0.5) blur(10px);
}

Ejemplos del uso de la función  con el recurso SVG se muestran a continuación.

.target { filter: url(#c1); }

.mydiv { filter: url(commonfilters.xml#large-blur) }

Funciones

Para utilizar la propiedad CSS filter, hay que especificar un valor para una de las siguientes funciones. Si el valor no es válido, la función se ejecutara de la misma manera que si se le aplicara  "none". Las funciones que toman un valor en procentaje (como en el 34%) también aceptan el valor expresado como decimal (como en 0.34 ó .34).

url()

La función url() coge de la dirección de un archivo XML que especifica un filtro SVG y puede incluir un ancla para un elemento de filtro especifico.

filter: url(resources.svg#c1)

blur()

Aplica un desenfoque Gaussiano a la imagen. El valor de 'radio' define el valor de la desviacion estándar de la función de desenfoque Gaussiano o el número de píxeles que se mezclan entre sí, por lo que un valor mayor creará un mayor desenfoque. Si no se proporciona ningún parametro, se utiliza un valor de 0. El parámetro se especifica como una medida de CSS, pero no acepta porcentages.

filter: blur(5px)
<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="svgBlur" x="-5%" y="-5%" width="110%" height="110%">
    <feGaussianBlur in="SourceGraphic" stdDeviation="5"/>
  </filter>
</svg>

brightness()

Se aplica una multiplicación lineal a la imagen, haciendo que parezca más o menos brillante. Un valor de 0% convertira la imagen completamente a negro. Un valor de 100% no producira ningun cambio en la imagen. Otros valores causaran una multiplicacion lineal en el efecto. Los valores de una cantidad superior al 100% aumentaran el brillo de la imagen, si no se especifica ningun valor se utilizara un valor de 1 (igual a 100%).

filter: brightness(0.5)
<svg height="0" xmlns="http://www.w3.org/2000/svg">
 <filter id="brightness">
    <feComponentTransfer>
        <feFuncR type="linear" slope="[amount]"/>
        <feFuncG type="linear" slope="[amount]"/>
        <feFuncB type="linear" slope="[amount]"/>
    </feComponentTransfer>
  </filter>
</svg>

contrast()

Adjusts the contrast of the input. A value of 0% will create an image that is completely black. A value of 100% leaves the input unchanged. Values of amount over 100% are allowed, providing results with less contrast. If the ‘amount’ parameter is missing, a value of 1 is used.

filter: contrast(200%)
<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="contrast">
    <feComponentTransfer>
      <feFuncR type="linear" slope="[amount]" intercept="-(0.5 * [amount]) + 0.5"/>
      <feFuncG type="linear" slope="[amount]" intercept="-(0.5 * [amount]) + 0.5"/>
      <feFuncB type="linear" slope="[amount]" intercept="-(0.5 * [amount]) + 0.5"/>
    </feComponentTransfer>
  </filter>
</svg>

drop-shadow()

Applies a drop shadow effect to the input image. A drop shadow is effectively a blurred, offset version of the input image's alpha mask drawn in a particular color, composited below the image. The function accepts a parameter of type <shadow> (defined in CSS3 Backgrounds), with the exception that the ‘inset’ keyword is not allowed. This function is similar to the more established box-shadow property; the difference is that with filters, some browsers provide hardware acceleration for better performance. The parameters of the <shadow> parameter are as follows.

<offset-x> <offset-y> (required)
This are two <length> values to set the shadow offset. <offset-x> specifies the horizontal distance. Negative values place the shadow to the left of the element. <offset-y> specifies the vertical distance. Negative values place the shadow above the element. See <length> for possible units.
If both values are 0, the shadow is placed behind the element (and may generate a blur effect if <blur-radius> and/or <spread-radius> is set).
<blur-radius> (optional)
This is a third <length> value. The larger this value, the bigger the blur, so the shadow becomes bigger and lighter. Negative values are not allowed. If not specified, it will be 0 (the shadow's edge is sharp).
<spread-radius> (optional)
This is a fourth <length> value. Positive values will cause the shadow to expand and grow bigger, and negative values will cause the shadow to shrink. If not specified, it will be 0 (the shadow will be the same size as the element). 
Note: Webkit, and maybe other browsers, do not support this 4th length; it will not render if added.
<color> (optional)
See <color> values for possible keywords and notations. If not specified, the color depends on the browser. In Gecko (Firefox), Presto (Opera) and Trident (Internet Explorer), the value of the color property is used. On the other hand, WebKit's shadow is transparent and therefore useless if <color> is omitted.
filter: drop-shadow(16px 16px 10px black)
<svg height="0" xmlns="http://www.w3.org/2000/svg">
 <filter id="drop-shadow">
    <feGaussianBlur in="SourceAlpha" stdDeviation="[radius]"/>
    <feOffset dx="[offset-x]" dy="[offset-y]" result="offsetblur"/>
    <feFlood flood-color="[color]"/>
    <feComposite in2="offsetblur" operator="in"/>
    <feMerge>
      <feMergeNode/>
      <feMergeNode in="SourceGraphic"/>
    </feMerge>
  </filter>
</svg>

grayscale()

Converts the input image to grayscale. The value of ‘amount’ defines the proportion of the conversion. A value of 100% is completely grayscale. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. If the ‘amount’ parameter is missing, a value of 0 is used.

filter: grayscale(100%)

hue-rotate()

Applies a hue rotation on the input image. The value of ‘angle’ defines the number of degrees around the color circle the input samples will be adjusted. A value of 0deg leaves the input unchanged. If the ‘angle’ parameter is missing, a value of 0deg is used. Though there is no maximum value, the effect of values above 360deg wraps around.

filter: hue-rotate(90deg)
<svg height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="svgHueRotate" >
    <feColorMatrix type="hueRotate" values="[angle]" />
  <filter />
</svg>

invert()

Inverts the samples in the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 100% is completely inverted. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. If the ‘amount’ parameter is missing, a value of 0 is used.

filter: invert(100%)

opacity()

Applies transparency to the samples in the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 0% is completely transparent. A value of 100% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. This is equivalent to multiplying the input image samples by amount. If the ‘amount’ parameter is missing, a value of 1 is used. This function is similar to the more established opacity property; the difference is that with filters, some browsers provide hardware acceleration for better performance.

filter: opacity(50%)

saturate()

Saturates the input image. The value of ‘amount’ defines the proportion of the conversion. A value of 0% is completely un-saturated. A value of 100% leaves the input unchanged. Other values are linear multipliers on the effect. Values of amount over 100% are allowed, providing super-saturated results. If the ‘amount’ parameter is missing, a value of 1 is used.

filter: saturate(200%)

sepia()

Converts the input image to sepia. The value of ‘amount’ defines the proportion of the conversion. A value of 100% is completely sepia. A value of 0% leaves the input unchanged. Values between 0% and 100% are linear multipliers on the effect. If the ‘amount’ parameter is missing, a value of 0 is used.

filter: sepia(100%)

Combining functions

You may combine any number of functions to manipulate the rendering. The following example enhances the contrast and brightness of the image.

filter: contrast(175%) brightness(3%)

Specifications

Specification Status Comment
Filter Effects Module Level 1
The definition of 'filter' in that specification.
Working Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 18.0-webkit [4] 35 (35) [1] [2] No support [3] 15.0-webkit 6.0-webkit
On SVG Elements No support (See bug 109224) 35 (35) No support No support No support
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 4.4-webkit 35 (35) [1] [2] No support 22.0 (Yes)-webkit

6.0 (Yes)-webkit

On SVG Elements No support (See bug 109224) 35 (35) No support No support No support

[1] Before Firefox 34, Gecko only implements the url() form of the filter property; as chaining was not implemented then, only one url() was allowed (or when the layout.css.filters.enabled pref is set to false).

[2] The functional values of filter is controlled by the layout.css.filters.enabled pref and was available but disabled by default in Firefox 34.

[3] Internet Explorer 4.0 to 9.0 implemented a non-standard filter property. The syntax was completely different from this one and is not documented here.

[4] In Chrome 18 to 19, saturate() function only takes integers instead of decimal or percentage values. This bug is fixed in Chrome 20 and further.

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: Sebastianz, teoli, maiky
 Última actualización por: Sebastianz,