4wk_
4wk_

Reputation: 2743

CSS: background-color and icon - inverting masks

here is a tough one. Let's imagine I have div, with a specific size (width and height), and a background-color: pink;. Now let's say I have a icon, a png file (or svg or anything), and I want the image to "dig" into the background color. In other words, I want the icon to be displayed in transparent, and the pink all around it. Like this: example It is just like the mask-image property, just the opposite.


Details:

Here are two PNG to match with the background-color:

stackoverflow pacman


Related:


Do you guys have any clue to achieve this behaviour? Let me know if you need more details.

Upvotes: 9

Views: 4875

Answers (2)

Ohara
Ohara

Reputation: 11

I'm a little bit late to the party, but for anyone stumbling upon this question, this problem has become really easy to solve with the introduction of the mask-composite property.

The idea in the following snippet is to create a completely filled "base layer" for the mask, and then use mask-composite: exclude to cut away the icon from the base layer.

* {
  height: 100%;
  margin: 0;
}
body {
  background-image: linear-gradient(aqua,blue);
}
div {
  background-color: pink;
  mask-image: 
    url("https://i.sstatic.net/SAaM7s.png"),
    linear-gradient(#fff, #fff);
  mask-position: center;
  mask-composite: exclude;
  mask-repeat: no-repeat;
}
<div />

Upvotes: 1

Takit Isy
Takit Isy

Reputation: 10081

You may want to use filter: invert(1); on the image when inside the div:

The image does not dig inside the div, but that visually works if the color behind the div is the same. (I've added a different color on the body to illustrate that unwanted behavior)

body{
  background: #ddd;
}

div {
  width: 200px;
  height: 140px;
  background-color: pink;
}

div img {
  /* You may want to add brightness(0) before invert for some images */
  filter: invert(1); 
}
<body>
  <div class="img_container">
    <img src="https://image.flaticon.com/icons/png/128/61/61072.png" />
  </div>
  <p>Original image:</p>
  <img src="https://image.flaticon.com/icons/png/128/61/61072.png" />
</body>

Note that I didn't use your images because it's not only black and transparent.

Upvotes: -2

Related Questions