What are the magical uses of CSS filter

Time:2021-7-25

background

Basic concepts

CSS filter  Attribute applies graphic effects such as blur or color offset to elements to form filters, which are 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 forfilter  and  backdrop-filter  Properties. 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 dimmer
  • contrast(): increase or decrease the contrast of the image
  • drop-shadow(): apply projection behind 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

Usage example

/*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 variable*/
filter: inherit;
filter: initial;
filter: unset;

What are the magical uses of CSS filter

Application case

More intelligent shadow effect

When adding shadows to elements, we usually usebox-shadowProperties, byBox shadow (x offset, y offset, blur size, shadow size, color value, inset)It’s easy to add shadow effects to elements, butbox-shadowThere is also a disadvantage, that is, when adding shadow effects to transparent pictures, elements cannot be penetrated and can only be added to the box model of transparent picture elements. At this time,filterAttributedrop-shadowMethod can solve this problem. The shadow added by it can penetrate the element rather than add it to the box model border of the element.

drop-shadowIn addition to penetrating transparent elements, the added shadow has the same effect asbox-shadowIs the same. If the browser supports hardware acceleration, usefilterThe added shadow effect is more realistic.

drop-shadowThe syntax is as follows (except that it does not support settings)inset, others andbox-shadowAre identical):

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 following figure is used separatelybox-shadowandfilter: drop-shadowAdd shadow contrast to transparent elements:

What are the magical uses of CSS filter

<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 and web pages are grayed out

In the event of major disasters, accidents or other mourning days, the government websites of state-owned enterprises often have the demand for all pages to be grayed out. Or many web pages have a mousehoverA style effect that becomes colored when suspended on gray elements. You can now usefilterAttributegrayscaleMethod, which can adjust the gray level of elements by setting page elementsfilter: grayscale(100%)The page elements can be grayed out. 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.png" />
</body>

What are the magical uses of CSS filter

Now let’s givebodyElement to add a.grayClass,<body class="gray">The whole web page can be grayed out.

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

What are the magical uses of CSS filter

For compatibilityIE8And other low version browsers, we can add browser prefix 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 making an emergency ash disposal web page, 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 ash disposal effect, so that it can be removed automatically at the scheduled 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');
  }
})();

Element emphasis and highlight

brightnessMethod to achieve the effect of element highlighting, which can be applied to menu bar and picture listhoverEffect to emphasize the content currently suspended or selected by the mouse. The following is a list of buttons added to the menu barbrightnessandsaturateTwo methods to highlight elements by changing brightness and saturation.

What are the magical uses of CSS filter

<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)Effect, as the name suggests, is similar to the effect of translucent ground glassiOSSystemWindows 10Such systemUIThe use of ground glass effect can enhance the visual experience. stayCSS uncover secretsAnd other works also have systematic explanations. Here are my views on their respective usefilter: blurandbackdrop-filter: blurTwo methods to achieve this effect are summarized.

There are two classes with the same class nameglassYesdivElement, which are added to two classes respectivelyglass-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 size, fillet and other basic styles of ground 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: blurMethod to add a::beforePseudo class settingsblurThe method is to place it on the bottom layer of glass and realize the 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 on 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):

What are the magical uses of CSS filter

Reading: extended frosted glass border effect:https://css-tricks.com/blurre…
What are the magical uses of CSS filter

Art photo! You can even implement a simple versioninsatagram

Retro, printmaking, oil painting, comics, liquefaction, old photos, sexual indifference, Morandi, cyberpunk, Wanda illusion style can all be realized!

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

What are the magical uses of CSS filter

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#imageContainerContains aimgElement, generatedfilterThe 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 + '%)'
  );
}
//When the input value changes, the filter is applied immediately
$("input[type=range]").change(editImage).mousemove(editImage);

Now only the real-time preview of the filter is realized, and the subsequent functions to be realized include supporting complexsvgFilter template, export and download, etc. after completing these steps, you don’t have to download other photos to add filters in the futureAPP😅Yes. Instance full version code:https://codepen.io/dragonir/p…

Save space and improve web page loading speed

Practice has proved that the volume of the same picture after reducing brightness, contrast and hue saturation can reduce a large part of the volume space compared with the original picture2MAfter the left and right pictures are weakened and saved, they can be compressed to1Mabout. In the web page, we can useweakenAnd then throughCSS filterRestore it. In this way, we can compress the resource volume, improve the web page loading speed and improve the user experience.

You can read the following tutorials for specific operations:

Contrast switching technology: UsingCSS filterImprove image performancehttps://css-tricks.com/contra…

compatibility

fromcaniuseAs can be seen from the query results,css filterProperties are well supported in modern browsers, exceptIEExcept for browsers, most other browsers can be used normally. If necessary, the browser kernel prefix can be added. However, the official website also has the following three issue tips. I believe these problems will be gradually repaired with the subsequent upgrade of the browser:

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

What are the magical uses of CSS filter

summary

This article simply lists several usesCSS filterCommonly used page effects, in factfilterEach of the built-in methods can have unlimited possible extended applications, such asinvertReverse colors can also be applied tohoverEffect, adjust the web pagesepiaBrown value can achieve eye protection effect, etc. As long as you use your imagination and creativity,filterCan be well applied in practice.

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

Finally, attach a filter editor called out aboveRetro Morandi color coldness oil painting effectFilter image( Wow, that’s too wow,CSSJujueziyyds🤣

What are the magical uses of CSS filter

Article address:https://segmentfault.com/a/11…Author: dragonir