Since the last post on CSS was popular here is another simple CSS trick that I found useful in the past.
Let’s say we want to find the difference between these two images:
You can do this by inverting the colors then stacking them together at 50% opacity. This could be done very easily using CSS filters:
-webkit-filter: invert(100%) opacity(50%);
The resulting image will be gray except for places where the two original images differ. This works because inverting will flip the color (e.g., 255 - c) and opacity will blend the two colors equally (e.g., c1 + c2 / 2). So the resulting color is ((255 - c1) + c2) / 2 which is just rgb(127.5, 127.5, 127.5) whenever the overlapping pixel colors c1 and c2 are the same.
Firefox 34 and older doesn’t support this but you can fallback to an equivalent SVG filter:
filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='invert' color-interpolation-filters='srgb'><feColorMatrix color-interpolation-filters='srgb' in='SourceGraphic' type='matrix' values='-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 0 0.5'/></filter></svg>#invert");
Or use mix-blend-mode: difference which actually produces prettier diffs (but isn’t supported on Chrome).
Being able to do the visual diff using pure CSS is nice because you can do it even if you don’t have access to the pixel data (which is typically only available by loading the image into a canvas or using Chrome extension’s captureVisibleTab). But with CSS you can do a visual diff against arbitrary elements rendered in the page as long as you can overlap things with it.
In particular, let’s say your designer mocked up something in Photoshop and gave it to you as a png to build. To layout elements matching the design, the usual workflow might involve manually measuring dimensions or overlaying a semitransparent mockup as a template. This process is usually pretty tedious since humans are surprisingly bad at detecting changes so you might miss subtle differences between the design and what you built.
To alleviate that a bit you can use this CSS trick to get a quick visual diff. For a concrete example, let’s say someone gave you a screenshot of google and asked you to replicate the html for it. To help position things you can overlay the inverted mock (see first section of the js tab) and then fiddle with the dimensions/margin/padding in inspector until everything is aligned, which looks something like this:
See the Pen vEGmKR by Franklin Ta (@fta) on CodePen.
When everything is solid gray, you know you got everything pixel perfect. (Note that small differences might not stand out against the gray, like forgetting a 2px border-radius or a subtle linear gradient.)
Great effect! Though I keep thinking in what other situations I could use this.
that’s great, good idea
The background-blend-mode property has a value of ‘difference’ which gives you a similar effect if your comparing two background-images:
http://codepen.io/bennettfeely/pen/NGdzjr