What’s the magic use of CSS filter

Time:2021-7-20

background

Basic concepts

CSS filterAttribute applies blur or color shift to elements to form a filter, which is usually used to adjust the rendering of images, backgrounds, and borders. Its value can befilterfunction<filter-function>Or useurlAdded SVG filter.


filter: <filter-function> [<filter-function>]* | none
filter: url(file.svg#filter-element-id)

<filter-function>Can be used forfilterandbackdrop-filterProperty. Its data type is specified by one of the following filter functions. Each function requires one 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(): blur image
  • brightness(): make the image brighter or dimmer
  • contrast(): increase or decrease the contrast of the image
  • drop-shadow(): apply projection to the back of the image
  • grayscale(): convert image to grayscale
  • hue-rotate(): change the overall tone of the image
  • invert(): invert image color
  • opacity(): change image transparency
  • saturate(): supersaturated or desaturated input image
  • sepia(): turns the image to tan

Examples of usage

/*Using SVG filter*/
filter: url("filters.svg#filter-id");
/*Using the filter function*/
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%);
/*Multiple filters*/
filter: contrast(175%) brightness(3%);
/*Do not use filter*/
filter: none;
/*Global variables*/
filter: inherit;
filter: initial;
filter: unset;

Application cases

More intelligent shadow effect

When adding shadows to elements, we usually usebox-shadowProperties, viaBox shadow (x offset, y offset, blur size, shadow size, color value, inset)It’s easy to add shadows to elements, butbox-shadowThere is also a disadvantage, that is, when adding shadow effect to transparent image, it can not penetrate the element, and can only be added to the box model of transparent image element. At this time,filterAttributedrop-shadowMethod can solve this problem very well. The shadow added with it can penetrate the element instead of being added to the box model border of the element.

drop-shadowThe added shadow can not only penetrate transparent elements, but also has the same effect as the shadowbox-shadowIf the browser supports hardware acceleration, usefilterThe added shadow effect will be more realistic.

drop-shadowThe syntax is as follows (except that it does not support settings)inset, others andbox-shadowIt’s exactly the same:

Filter: Drop Shadow (x offset, y offset, blur size, color value);

For example:


filter: drop-shadow(1px 1px 15px rgba(0, 0, 0, .5));

The figure below shows how to use thebox-shadowandfilter: drop-shadowContrast of shading transparent elements:


<img class="box-shadow" src="futurama.jpg" />
<img class="drop-shadow" src="futurama.jpg" />

.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));
}

Graying elements and web pages

In the event of major disasters or other days of mourning, the government websites of state-owned enterprises often have the demand to put all the webpages in gray. Or many web pages have a mousehoverA style effect that becomes colored when suspended over a gray element. You can use thefilterAttributegrayscaleMethod, which can adjust the gray level of the elements by setting thefilter: grayscale(100%)You can gray out the page elements. In the following example,bodyUnder the labelh1andimgLabel, not addedfilterThe front of the style is shown below.


<body>
  <h1 class="title">FUTURAMA</h1>
  <img class="img" width="500" src="./images/futurama.jpg" />
</body>

Now let’s give it to youbodyElement to add a.grayClass,<body>Can achieve the entire web page graying effect.


.gray {
  filter: grayscale(100%);
}

For compatibilityIE8And other low-level browsers, we can add browser prefixes andsvgFilter.😤


.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%);
}

When we need to do the emergency ashing web page, we often need to remove this function when we go online for a period of time. We can also add the following similar methods when we go online for the first time to control the automatic time of ashing effect. In this way, we can automatically remove the function when we reach the predetermined time, without going through two construction processes.🤣


(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');
  }
})();

Emphasis and highlight of elements

brightnessMethod to achieve the effect of element highlight, which can be applied to menu bar and picture listhoverEffect, to emphasize the current mouse hover or selected content. Here’s a list of buttons to add to the menu barbrightnessandsaturateTwo methods, by changing the brightness and saturation to highlight elements.


<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%);
}

Ground glass effect

Ground glass(Frosted glass)The effect, as the name suggests, is similar to the effect of translucent ground glassiOSSystemWindows 10And so onUIThe use of ground glass can enhance the visual experience. stayRevealing the secrets of CSSAnd other works also have a systematic explanation, the following is what I use separatelyfilter: blurandbackdrop-filter: blurTwo methods to achieve this effect are summarized.

Two have the same class nameglassOfdivElement, which are added to two classesglass-by-filterandglass-by-backdrop-filterTo distinguish between the two methods.


<div class="glass glass-by-filter"></div>
<div class="glass glass-by-backdrop-filter"></div>

General style: set the basic styles of ground glass elements such as size and fillet


.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: blurMethod to add a::beforePseudo class settingsblurMethod and put it in the bottom layer to achieve the ground 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: blurAdd directly to the elementblurMethods the ground glass effect was achieved.


.glass-by-backdrop-filter {
  backdrop-filter: blur(10px);
}

The implementation effect is shown in the figure below (left:filter, right:backdrop-filter):

Reading expansion: ground glass frame effect:https://css-tricks.com/blurred-borders-in-css

Art photo! You can even implement a simple versioninsatagram

Retro, printmaking, oil painting, comics, liquefaction, old photos, sex indifference, Morandi, cyberpunk, Wanda illusion style can be achieved!

By combiningfilterAll of the methods, you can match any effect you want. Here is a simple examplefilterMethod adjuster, which can adjust the value of each method, and display the filter effect of the image in real time. As shown in the figure below.

The main code of the page is as follows, control area#imageEditorIt’s aformForm, each line of the form controls the value of a filter method, and the display area#imageContainerIt contains aimgElement, producedfilterThe filter acts on the 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.jpg">
</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 + '%)'
  );
}
//The filter is applied immediately when the input value changes
$("input[type=range]").change(editImage).mousemove(editImage);

Now we only realize the real-time preview of the filter, and the functions to be implemented include supporting complex filteringsvgFilter template, export and download, complete these steps, after the photo add filter no longer need to download otherAPP😅It’s too late. Example full version code:https://codepen.io/dragonir/pen/abJmqxM

Save space and improve the loading speed of web pages

Practice has proved that the same image after reducing the brightness and contrast and hue saturation can reduce a large part of the volume space compared with the original image2MThe left and right images can be compressed to1Mabout. In the web page, we can use theweakenAnd then through theCSS filterRestore it. In this way, the volume of resources can be compressed, the loading speed of web pages can be improved, and the user experience can be improved.

For specific operation, please read the following tutorial:

Contrast exchange technology: UsingCSS filterImprove image performancehttps://css-tricks.com/contrast-swap-technique-improved-image-performance-css-filters

compatibility

fromcaniuseThe query results show that,css filterProperties are well supported in modern browsers, exceptIEIn addition to the browser, most other browsers can be used normally, and the browser kernel prefix can be added when necessary. However, the official website also has the following three issues. I believe that with the upgrade of the browser, these problems will be gradually fixed:

  • In Safari browser, if the child element has animation effect, it will not be applied filter.
  • There is currently no browser supportdrop-shadowFilter’sspread-radiusmethod.
  • stayEdgeIf the element or child element is set in the browserNegative Z-index, the filter cannot be applied.

summary

This article simply lists several usesCSS filterCommonly used page effect, in factfilterEach of the built-in methods of can have unlimited expansion applications, such asinvertReverse colors can also be applied tohoverEffect, adjust the pagesepiaBrown value can achieve eye protection effect. Just use your imagination and creativity,filterAll of them can be well applied in practice.

The following examples are good applications. If you are interested, you can expand reading learning:

Ground glass effecthttps://codepen.io/KazuyoshiGoto/pen/nhstF

Broken glass effecthttps://codepen.io/bajjy/pen/vwrKk

Using filter to achieve the hover effecthttps://codepen.io/nxworld/details/ZYNOBZ

Reverse buttonhttps://codepen.io/monkey-company/pen/zZZvRp

Old photoshttps://codepen.io/dudleystorey/pen/pKoqa

Advanced filter editor:https://codepen.io/stoumann/pen/MWeNmyb

At last, I attach a picture which is adjusted by the above filter editorThe effect of retro Morandi's cool oil paintingFilter image( Wow, that’s too much,CSSJue Jue Ziyyds🤣

The above is the details of the magical use of CSS filter. For more information about the magical use of CSS filter, please pay attention to other related articles of developer!