Тип CSS `<filter-function>`
Базовая поддержка Широко доступно
Эта возможность хорошо зарекомендовала себя и работает на многих устройствах и во многих версиях браузеров. Она доступна во всех браузерах с сентября 2016 года.
<filter-function> CSS — это тип данных, представляющий графический эффект, который может изменять внешний вид входного изображения. Он используется в свойствах filter и backdrop-filter.
Синтаксис
Тип данных <filter-function> задается с помощью одной из перечисленных ниже функций фильтра. Каждая функция принимает аргумент, который при недопустимом значении приводит к тому, что фильтр не применяется.
-
blur() - Размывает изображение.
-
brightness() - Делает изображение светлее или темнее.
-
contrast() - Увеличивает или уменьшает контрастность изображения.
-
drop-shadow() - Добавляет тень за изображением.
-
grayscale() - Преобразует изображение в оттенки серого.
-
hue-rotate() - Изменяет общий оттенок изображения.
-
invert() - Инвертирует цвета изображения.
-
opacity() - Делает изображение прозрачным.
-
saturate() - Значительно увеличивает или уменьшает насыщенность входного изображения.
-
sepia() - Преобразует изображение в сепию.
Формальный синтаксис
<filter-function> = <blur()> | <brightness()> | <contrast()> | <drop-shadow()> | <grayscale()> | <hue-rotate()> | <invert()> | <opacity()> | <saturate()> | <sepia()> <blur()> = blur( <length>? ) <brightness()> = brightness( [ <number> | <percentage> ]? ) <contrast()> = contrast( [ <number> | <percentage> ]? ) <drop-shadow()> = drop-shadow( [ <color>? && <length>{2,3} ] ) <grayscale()> = grayscale( [ <number> | <percentage> ]? ) <hue-rotate()> = hue-rotate( [ <angle> | <zero> ]? ) <invert()> = invert( [ <number> | <percentage> ]? ) <opacity()> = opacity( [ <number> | <percentage> ]? ) <saturate()> = saturate( [ <number> | <percentage> ]? ) <sepia()> = sepia( [ <number> | <percentage> ]? ) <color> = <color-base> | currentColor | <system-color> | <light-dark()> | <deprecated-system-color> <color-base> = <hex-color> | <color-function> | <named-color> | <color-mix()> | transparent <system-color> = AccentColor | AccentColorText | ActiveText | ButtonBorder | ButtonFace | ButtonText | Canvas | CanvasText | Field | FieldText | GrayText | Highlight | HighlightText | LinkText | Mark | MarkText | SelectedItem | SelectedItemText | VisitedText <light-dark()> = light-dark( <color>, <color> ) <deprecated-system-color> = ActiveBorder | ActiveCaption | AppWorkspace | Background | ButtonHighlight | ButtonShadow | CaptionText | InactiveBorder | InactiveCaption | InactiveCaptionText | InfoBackground | InfoText | Menu | MenuText | Scrollbar | ThreeDDarkShadow | ThreeDFace | ThreeDHighlight | ThreeDLightShadow | ThreeDShadow | Window | WindowFrame | WindowText <color-function> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hwb()> | <lab()> | <lch()> | <oklab()> | <oklch()> | <color()> <named-color> = aliceblue | antiquewhite | aqua | aquamarine | azure | beige | bisque | black | blanchedalmond | blue | blueviolet | brown | burlywood | cadetblue | chartreuse | chocolate | coral | cornflowerblue | cornsilk | crimson | cyan | darkblue | darkcyan | darkgoldenrod | darkgray | darkgreen | darkgrey | darkkhaki | darkmagenta | darkolivegreen | darkorange | darkorchid | darkred | darksalmon | darkseagreen | darkslateblue | darkslategray | darkslategrey | darkturquoise | darkviolet | deeppink | deepskyblue | dimgray | dimgrey | dodgerblue | firebrick | floralwhite | forestgreen | fuchsia | gainsboro | ghostwhite | gold | goldenrod | gray | green | greenyellow | grey | honeydew | hotpink | indianred | indigo | ivory | khaki | lavender | lavenderblush | lawngreen | lemonchiffon | lightblue | lightcoral | lightcyan | lightgoldenrodyellow | lightgray | lightgreen | lightgrey | lightpink | lightsalmon | lightseagreen | lightskyblue | lightslategray | lightslategrey | lightsteelblue | lightyellow | lime | limegreen | linen | magenta | maroon | mediumaquamarine | mediumblue | mediumorchid | mediumpurple | mediumseagreen | mediumslateblue | mediumspringgreen | mediumturquoise | mediumvioletred | midnightblue | mintcream | mistyrose | moccasin | navajowhite | navy | oldlace | olive | olivedrab | orange | orangered | orchid | palegoldenrod | palegreen | paleturquoise | palevioletred | papayawhip | peachpuff | peru | pink | plum | powderblue | purple | rebeccapurple | red | rosybrown | royalblue | saddlebrown | salmon | sandybrown | seagreen | seashell | sienna | silver | skyblue | slateblue | slategray | slategrey | snow | springgreen | steelblue | tan | teal | thistle | tomato | turquoise | violet | wheat | white | whitesmoke | yellow | yellowgreen <color-mix()> = color-mix( <color-interpolation-method> , [ <color> && <percentage [0,100]>? ]#{2}) <rgb()> = rgb( <percentage>#{3} , <alpha-value>? ) | rgb( <number>#{3} , <alpha-value>? ) | rgb( [ <number> | <percentage> | none ]{3} [ / [ <alpha-value> | none ] ]? ) <rgba()> = rgba( <percentage>#{3} , <alpha-value>? ) | rgba( <number>#{3} , <alpha-value>? ) | rgba( [ <number> | <percentage> | none ]{3} [ / [ <alpha-value> | none ] ]? ) <hsl()> = hsl( <hue>, <percentage>, <percentage>, <alpha-value>? ) | hsl( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? ) <hsla()> = hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ) | hsla( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? ) <hwb()> = hwb( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? ) <lab()> = lab( [<percentage> | <number> | none] [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ / [<alpha-value> | none] ]? ) <lch()> = lch( [<percentage> | <number> | none] [ <percentage> | <number> | none] [ <hue> | none] [ / [<alpha-value> | none] ]? ) <oklab()> = oklab( [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ / [<alpha-value> | none] ]? ) <oklch()> = oklch( [ <percentage> | <number> | none] [ <percentage> | <number> | none] [ <hue> | none] [ / [<alpha-value> | none] ]? ) <color()> = color( [ from <color> ]? <colorspace-params> [ / [ <alpha-value> | none ] ]? ) <color-interpolation-method> = in [ <rectangular-color-space> | <polar-color-space> <hue-interpolation-method>? | <custom-color-space> ] <alpha-value> = <number> | <percentage> <hue> = <number> | <angle> <colorspace-params> = [<custom-params> | <predefined-rgb-params> | <xyz-params>] <rectangular-color-space> = srgb | srgb-linear | display-p3 | display-p3-linear | a98-rgb | prophoto-rgb | rec2020 | lab | oklab | xyz | xyz-d50 | xyz-d65 <polar-color-space> = hsl | hwb | lch | oklch <hue-interpolation-method> = [ shorter | longer | increasing | decreasing ] hue <custom-color-space> = <dashed-ident> <custom-params> = <dashed-ident> [ <number> | <percentage> | none ]+ <predefined-rgb-params> = <predefined-rgb> [ <number> | <percentage> | none ]{3} <xyz-params> = <xyz> [ <number> | <percentage> | none ]{3} <predefined-rgb> = srgb | srgb-linear | display-p3 | display-p3-linear | a98-rgb | prophoto-rgb | rec2020 <xyz> = xyz | xyz-d50 | xyz-d65
Примеры
Сравнение функций фильтра
В этом примере представлены изображение, раскрывающееся меню для выбора типа функции фильтра и ползунок для изменения значений, используемых внутри функции фильтра. При изменении элементов управления эффект фильтра обновляется в реальном времени, что позволяет изучить действие различных фильтров.
В раскрывающемся списке выбирается имя функции, а с помощью ползунка задается значение параметра этой функции. Для drop-shadow значение используется и для горизонтального, и для вертикального смещения, а радиус равен половине этого значения.
<div></div>
<ul>
<li>
<label for="filter-select">Choose a filter function:</label>
<select id="filter-select">
<option selected>blur</option>
<option>brightness</option>
<option>contrast</option>
<option>drop-shadow</option>
<option>grayscale</option>
<option>hue-rotate</option>
<option>invert</option>
<option>opacity</option>
<option>saturate</option>
<option>sepia</option>
</select>
</li>
<li><input type="range" /><output></output></li>
<li>
<p>Current value: <code></code></p>
</li>
</ul>
div {
width: 100%;
height: 512px;
background-image: url("https://mdn.github.io/shared-assets/images/examples/fx-nightly-512.png");
background-repeat: no-repeat;
background-position: center center;
}
li {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
}
input {
width: 60%;
}
output {
width: 5%;
text-align: center;
}
select {
width: 40%;
margin-left: 2px;
}
const selectElem = document.querySelector("select");
const divElem = document.querySelector("div");
const slider = document.querySelector("input");
const output = document.querySelector("output");
const curValue = document.querySelector("p code");
selectElem.addEventListener("change", () => {
setSlider(selectElem.value);
setDiv(selectElem.value);
});
slider.addEventListener("input", () => {
setDiv(selectElem.value);
});
function setSlider(filter) {
switch (filter) {
case "blur":
slider.value = 0;
slider.min = 0;
slider.max = 30;
slider.step = 1;
slider.setAttribute("data-unit", "px");
break;
case "brightness":
case "contrast":
case "saturate":
slider.value = 1;
slider.min = 0;
slider.max = 4;
slider.step = 0.05;
slider.setAttribute("data-unit", "");
break;
case "drop-shadow":
slider.value = 0;
slider.min = -20;
slider.max = 40;
slider.step = 1;
slider.setAttribute("data-unit", "px");
break;
case "opacity":
slider.value = 1;
slider.min = 0;
slider.max = 1;
slider.step = 0.01;
slider.setAttribute("data-unit", "");
break;
case "grayscale":
case "invert":
case "sepia":
slider.value = 0;
slider.min = 0;
slider.max = 1;
slider.step = 0.01;
slider.setAttribute("data-unit", "");
break;
case "hue-rotate":
slider.value = 0;
slider.min = 0;
slider.max = 360;
slider.step = 1;
slider.setAttribute("data-unit", "deg");
break;
default:
console.error("Unknown filter set");
}
}
function setDiv(filter) {
const unit = slider.getAttribute("data-unit");
const offset = `${Math.round(slider.value)}${unit}`;
const radius = `${Math.round(Math.abs(slider.value / 2))}${unit}`;
divElem.style.filter =
filter === "drop-shadow"
? `${selectElem.value}(${offset} ${offset} ${radius})`
: `${selectElem.value}(${slider.value}${unit})`;
updateOutput();
updateCurValue();
}
function updateOutput() {
output.textContent = slider.value;
}
function updateCurValue() {
curValue.textContent = `filter: ${divElem.style.filter}`;
}
setSlider(selectElem.value);
setDiv(selectElem.value);
Спецификации
Совместимость с браузерами
| Настольные компьютеры | Мобильные устройства | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome для Android | Firefox для Android | Opera для Android | Safari на iOS | Samsung Internet | WebView для Android | WebView на iOS | |
filter-function |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
blur |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
brightness |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
contrast |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
drop-shadow |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
grayscale |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
hue-rotate |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
invert |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
opacity |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
saturate |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
sepia |
18 |
12 |
35 |
15 |
6 |
53 |
35 |
14 |
6 |
6.0 |
4.4 |
6 |
См. также
- Свойства, использующие этот тип данных:
filterиbackdrop-filter
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/filter-function