use multiple css filters at the same time?

后端 未结 2 2010
萌比男神i
萌比男神i 2020-12-08 09:07

I am experimenting with css filters.

And I would like use the blur and grayscale at the same time, but I can\'t seem to use both simultaneously on the same image?

2条回答
  •  囚心锁ツ
    2020-12-08 10:03

    Because it's one property named filter, every time you want to add a style to it you override it.

    CSS version 1

    Fortunately you can add multiple styles in some properties like background-image and filter! To get this working you'll have to put all the filter styles in one space separated filter property.

    .grayscale.blur {
        filter: blur(5px) grayscale(1);
    }
    

    CSS version 2

    An alternative, flexible, solution would be to create a "div soup" on purpose and set different filters in the html stack. e.g.

    CSS version 3

    edit: just realised I just wrote this version with transforms, but the same idea applies.

    Yet another solution is CSS vars. I wouldn't say it's ideal but it's a nice experiment. The major downside is that you need to declare a lot of variables, have default long rules for transform and nested transforms will definitely break.

    // Added just for fun
    setInterval(() => {
      yes_this_works_and_one_of_many_reasons_ids_are_bad.classList.toggle('translate');
    }, 1000);
    setInterval(() => {
      yes_this_works_and_one_of_many_reasons_ids_are_bad.classList.toggle('scale');
    }, 1500);
    :root {
      --scale: 1;
      --translate: 0px;
    }
    .box {
      background: blue;
      width: 20px;
      height: 20px;
      transform: 
        scale(var(--scale))
        translate(var(--translate), var(--translate));
      transition: transform .3s;
    }
    .box.translate {
      --translate: 20px;
    }
    .box.scale {
      --scale: 3;
    }

    Javascript

    Lastly, if you were to use JavaScript to render the styles you can read the current applied filters using getComputedStyle and add more to the mix.

    • Modern browser demo setting styles nicely
    • Modern browser demo setting styles without respect and fix it with observers

    And a relevant article - this is more for animations and not yet supported by many browsers: Additive animations

    And another relevant article on css-tricks: Houdini

提交回复
热议问题