background
basic concept
CSS filter
Properties apply graphical effects such as blur or color shift to elements to form filters. Filters are often used to adjust the rendering of images, backgrounds, and borders. Its value can be filter
function <filter-function>
or use url
added svg filter.
filter: <filter-function> [<filter-function>]* | none
filter: url(file.svg#filter-element-id)
<filter-function>
can be used for filter
and backdrop-filter
attributes. Its data type is specified by one of the following filter functions. Each function requires a parameter, if the parameter is invalid, the filter will not take effect. The following is an explanation of the meaning of the filter function:
-
blur()
: blurred image -
brightness()
: make the image brighter or darker -
contrast()
: Increase or decrease the contrast of the image -
drop-shadow()
: apply a projection behind the image -
grayscale()
: Convert the image to grayscale -
hue-rotate()
: Change the overall tone of the image -
invert()
: Invert image colors -
opacity()
: Change image transparency -
saturate()
: supersaturated or desaturated input image -
sepia()
: Convert the image to sepia
Usage example
/* 使用SVG filter */
filter: url("filters.svg#filter-id");
/* 使用filter函数 */
filter: blur(5px);
filter: brightness(0.4);
filter: contrast(200%);
filter: drop-shadow(16px 16px 20px blue);
filter: grayscale(50%);
filter: hue-rotate(90deg);
filter: invert(75%);
filter: opacity(25%);
filter: saturate(30%);
filter: sepia(60%);
/* 多个filter */
filter: contrast(175%) brightness(3%);
/* 不使用filter */
filter: none;
/* 全局变量 */
filter: inherit;
filter: initial;
filter: unset;
Applications
Smarter shadow effects
When adding a shadow to an element, we generally use the box-shadow
attribute. It is easy to add a shadow effect to the element through the syntax form of box-shadow(x偏移, y偏移, 模糊大小, 阴影大小, 色值, inset)
79feecb6b4d4abbc7c8f8c1f0e0d78bf---, but box-shadow
also has a disadvantage , that is, when adding a shadow effect to a transparent image, it cannot penetrate the element and can only be added to the box model of the transparent image element. At this time, the drop-shadow
method of the filter
attribute can solve this problem very well. The shadow added by it can penetrate the element instead of adding it to the box model border of the element.
drop-shadow
Added shadow except that it can penetrate transparent elements, the shadow effect is the same as box-shadow
, if the browser supports hardware acceleration, use filter
added Shadow effects will be more realistic.
drop-shadow
has the following syntax (it is exactly the same as box-shadow
except that it does not support setting inset
):
filter: drop-shadow(x偏移, y偏移, 模糊大小, 色值);
Such as:
filter: drop-shadow(1px 1px 15px rgba(0, 0, 0, .5));
The following image is a comparison of using box-shadow
and filter: drop-shadow
to add shadows to transparent elements:
<img class="box-shadow" src="futurama.png" />
<img class="drop-shadow" src="futurama.png" />
.box-shadow {
box-shadow: 1px 1px 15px rgba(0, 0, 0, .5);
}
.drop-shadow {
filter: drop-shadow(1px 1px 15px rgba(0, 0, 0, .5));
}
Elements, pages are grayed out
In the event of major disasters or other mourning days, government websites of state-owned enterprises often require all pages to be grayed out. Or in many web pages, the mouse hover
has a colored style effect when hovering over a gray element. At this point, you can use the grayscale
method of the --- filter
attribute, which can adjust the grayscale of the element. By setting the page element filter: grayscale(100%)
, the page element can be grayed out . In the following example, under the body
tag, there are h1
and img
tags, as shown below without the filter
style.
<body>
<h1 class="title">FUTURAMA</h1>
<img class="img" width="500" src="./images/futurama.png" />
</body>
Now we add a .gray
class to the body
element, <body class="gray">
to achieve the graying effect of the entire web page.
.gray {
filter: grayscale(100%);
}
In order to be compatible with other lower version browsers such as IE8
, we can add the browser prefix and svg
filter. 😤
.gray {
-webkit-filter: grayscale(1);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
filter: grayscale(100%);
}
In the case of urgent gray page requirements, it is often necessary to remove this function after going online for a period of time. We can also add the following similar methods when going online for the first time to control the automatic online and offline time of the graying effect, so that the automatic online and offline time can be automatically reached when the preset time is reached. Removed, without having to go through the construction process twice. 🤣
(function setGray() {
var endTime = Date.parse("Apr 06 2077 00:00:01");
var timestamp = Date.parse(new Date());
if (timestamp <= endTime) {
document.querySelector('html').classList.add('gray');
}
})();
Element emphasis, highlighting
brightness
method to achieve the effect of element highlighting, which can be applied to the menu bar, picture list hover
effect, to emphasize the content currently suspended or selected by the mouse. The following is to add brightness
and saturate
two methods to the menu bar of a group of buttons to highlight elements by changing the brightness and saturation.
<div class="container">
<a class="button">🍋</a>
<a class="button">🍎</a>
<a class="button">🍐</a>
<a class="button dark">🥑</a>
<a class="button dark">🍄</a>
<a class="button dark">🌽</a>
<a class="button disabled">🍒</a>
<a class="button disabled">🍅</a>
<a class="button disabled">🥔</a>
</div>
.container {
margin: 40px;
}
.button {
padding: 0.5em 0.5em;
background: #E0E0E0;
border-radius: 3px;
}
.button.dark {
background: #333;
}
.button:hover:not(.disabled) {
cursor: pointer;
border-radius: 3px;
filter: brightness(110%) saturate(140%);
}
.button.disabled {
filter: grayscale(100%);
}
frosted glass effect
Frosted glass ( Frosted glass
) effect, by definition is similar translucent frosted glass effect, iOS
systems, Windows 10
systems UI
find wide application, use the frosted glass effect to enhance the visual experience. There are also systematic explanations in 《CSS揭秘》
and other works. The following is my summary of using filter: blur
and backdrop-filter: blur
respectively to achieve this effect.
There are two div
elements with the same class name glass
, and they are respectively added with two classes glass-by-filter
and glass-by-backdrop-filter
to distinguish the two method.
<div class="glass glass-by-filter"></div>
<div class="glass glass-by-backdrop-filter"></div>
General style, set basic styles such as the size and rounded corners of frosted glass elements:
.glass {
height: 300px;
width: 300px;
border: 1px groove #EFEFEF;
border-radius: 12px;
background: rgba(242, 242, 242, 0.5);
box-shadow: 0 0.3px 0.7px rgba(0, 0, 0, 0.126),
0 0.9px 1.7px rgba(0, 0, 0, 0.179), 0 1.8px 3.5px rgba(0, 0, 0, 0.224),
0 3.7px 7.3px rgba(0, 0, 0, 0.277), 0 10px 20px rgba(0, 0, 0, 0.4);
}
filter: blur
blur
, adds a ::before
pseudo-class setting to the element and places it on the bottom layer to achieve a frosted glass effect.
.glass-by-filter {
z-index: 1;
box-sizing: border-box;
position: relative;
}
.glass-by-filter::before {
content: "";
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
z-index: -1;
background: inherit;
filter: blur(10px);
}
backdrop-filter: blur
Add blur
method directly on the element to achieve the frosted glass effect.
.glass-by-backdrop-filter {
backdrop-filter: blur(10px);
}
The effect is shown in the following figure (left: filter
, right: backdrop-filter
):
Read the extension: Frosted glass border effect: https://css-tricks.com/blurred-borders-in-css
artistic photos! Even a simple version can be implemented insatagram
Retro, printmaking, oil painting, comics, liquefaction, old photos, frigidity, Morandi, cyberpunk, WandaVision styles are all available!
By combining all the methods of filter
, you can mix and match any effect you want. The following is a simple filter
method adjuster, which can adjust the value of each method, and show the filter effect of the picture in real time. As shown below.
The main code of the page is as follows. The control area #imageEditor
is a form
form. Each row of the form controls the value of a filter method. The display area #imageContainer
contains img
element, the resulting filter
filter acts on this element.
<form id="imageEditor">
<p>
<label for="gs">Grayscale</label>
<input id="gs" name="gs" type="range" min="0" max="100" value="0">
</p>
<p>
<label for="blur">Blur</label>
<input id="blur" name="blur" type="range" min="0" max="10" value="0">
</p>
<p>
<label for="br">Exposure</label>
<input id="br" name="br" type="range" min="0" max="200" value="100">
</p>
<p>
<label for="ct">Contrast</label>
<input id="ct" name="ct" type="range" min="0" max="200" value="100">
</p>
<p>
<label for="huer">Hue Rotate</label>
<input id="huer" name="huer" type="range" min="0" max="360" value="0">
</p>
<p>
<label for="opacity">Opacity</label>
<input id="opacity" name="opacity" type="range" min="0" max="100" value="100">
</p>
<p>
<label for="invert">Invert</label>
<input id="invert" name="invert" type="range" min="0" max="100" value="0">
</p>
<p>
<label for="saturate">Saturate</label>
<input id="saturate" name="saturate" type="range" min="0" max="500" value="100">
</p>
<p>
<label for="sepia">Sepia</label>
<input id="sepia" name="sepia" type="range" min="0" max="100" value="0">
</p>
<input type="reset" form="imageEditor" id="reset" value="Reset" />
</form>
<div id="imageContainer" class="center">
<img src="futurama.png">
</div>
function editImage() {
var gs = $("#gs").val(); // grayscale
var blur = $("#blur").val(); // blur
var br = $("#br").val(); // brightness
var ct = $("#ct").val(); // contrast
var huer = $("#huer").val(); // hue-rotate
var opacity = $("#opacity").val(); // opacity
var invert = $("#invert").val(); // invert
var saturate = $("#saturate").val(); // saturate
var sepia = $("#sepia").val(); // sepia
$("#imageContainer img").css(
"filter", 'grayscale(' + gs+
'%) blur(' + blur +
'px) brightness(' + br +
'%) contrast(' + ct +
'%) hue-rotate(' + huer +
'deg) opacity(' + opacity +
'%) invert(' + invert +
'%) saturate(' + saturate +
'%) sepia(' + sepia + '%)'
);
$("#imageContainer img").css(
"-webkit-filter", 'grayscale(' + gs+
'%) blur(' + blur +
'px) brightness(' + br +
'%) contrast(' + ct +
'%) hue-rotate(' + huer +
'deg) opacity(' + opacity +
'%) invert(' + invert +
'%) saturate(' + saturate +
'%) sepia(' + sepia + '%)'
);
}
// 当input值发生变化时即时应用滤镜
$("input[type=range]").change(editImage).mousemove(editImage);
Now only the real-time preview of the filter has been implemented. The subsequent functions to be implemented include support for complex svg
filter templates, export and download, etc. After completing these steps, you will no longer need to download other photos after adding filters APP😅
now. Example full version code: https://codepen.io/dragonir/pen/abJmqxM
Save space and improve web page loading speed
Practice has proved that the volume of the same image after reducing the brightness, contrast and 2M
saturation can reduce a large part of the volume space compared with the original image. 1M
or so. In the web page we can use the image that has passed ---f29c988565b8ce50ed6896ef0724fc9e 弱化
, and then restore it through CSS filter
. In this way, the purpose of compressing resource volume, improving web page loading speed, and improving user experience can be achieved.
For specific operations, read the following tutorials:
Contrast Swap Technique: Use CSS filter
to improve image performance https://css-tricks.com/contrast-swap-technique-improved-image-performance-css-filters
compatibility
From the caniuse
query result, we can see that the css filter
attribute is well supported in modern browsers, except IE
Most of the browsers can be used normally, and the browser kernel prefix can be added if necessary. However, the official website also has the following 3 issue tips. I believe that with the upgrade of the browser, these problems will be gradually fixed:
- In Safari, the filter is not applied if the child element is animated.
- There is currently no browser support for the
drop-shadow
filterspread-radius
method. - In
Edge
the filter cannot be applied if the element or child element is set to负值z-index
.
Summarize
This article simply enumerates several commonly used page effects CSS filter
filter
. In fact, each built-in method of ---3cce3ecd07aaa58ae68e8d3b24aa3f6e--- can have infinite possible extended applications, such as invert
Reverse color can also be applied to hover
effect, adjust web page sepia
brown value can achieve eye protection effect, etc. As long as you use your imagination and creativity, filter
can be well applied in practice.
The following examples are good applications, and you can expand your reading and learning if you are interested:
- Frosted glass effect https://codepen.io/KazuyoshiGoto/pen/nhstF
- Broken glass effect https://codepen.io/bajjy/pen/vwrKk
- The hover effect implemented by filter https://codepen.io/nxworld/details/ZYNOBZ
- Invert button https://codepen.io/monkey-company/pen/zZZvRp
- Old photos https://codepen.io/dudleystorey/pen/pKoqa
- Advanced filter editor: https://codepen.io/stoumann/pen/MWeNmyb
Finally, attach a filter image called 复古莫兰迪色性冷淡油画效果
filtered by the above filter editor. (Wow, this is too wow, CSS
yyds🤣
)
Article address: https://segmentfault.com/a/1190000040058430 Author: dragonir
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。