Applying multiple mask-image to a single div

Viewed 2980

I can apply a mask-image at any place on a div I want, but can I apply more than one mask-image on the same div?

Example with a single mask-image:

div {
  width: 200px;
  height: 200px;
  background-color: green;
  border: 2px solid black;
  
  -webkit-mask-image: radial-gradient(
    circle at center top,
    transparent 30px,
    black 31px
  );
}
<div></div>

What would the code look like if I wanted to have the same mask applied at the top and at the bottom at the same time?

div {
  width: 200px;
  height: 200px;
  background-color: green;
  border: 2px solid black;
  
  -webkit-mask-image: radial-gradient(
    circle at center top,
    transparent 30px,
    black 31px
  ), radial-gradient(
    circle at center bottom,
    transparent 30px,
    black 31px
  );
}
<div></div>

Edit: I'm aware Chrome supports mask-composite, but that works (at the time of writing this) only with Chrome.

1 Answers

You need to play with the size and position. mask work the same way as background-image so simply imagine your self making two images on the same element (one on the top and the other on the bottom)

div {
  width: 200px;
  height: 200px;
  background-color: green;
  border: 2px solid black;
  -webkit-mask: 
     radial-gradient( circle at center top,    transparent 30px, black 31px) top, 
     radial-gradient( circle at center bottom, transparent 30px, black 31px) bottom;
  -webkit-mask-size:100% 51%; /* each one half the size */
  -webkit-mask-repeat:no-repeat; /* don't forget this */
}
<div></div>

Another idea with one mask:

div {
  width: 200px;
  height: 200px;
  background-color: green;
  border: 2px solid black;
  -webkit-mask: radial-gradient(circle, transparent 30px, black 31px) 0 100px; /* 100px is half the height */
}
<div></div>

and with the border:

div {
  width: 200px;
  height: 200px;
  background: radial-gradient(circle, transparent 30px, black 0 33px,green 33px) 0 100px border-box;
  border: 2px solid black;
  -webkit-mask: radial-gradient(circle, transparent 30px, black 31px) 0 100px; /* 100px is half the height */
}
<div></div>


A solution with mask-composite:

div {
  width: 200px;
  height: 200px;
  background-color: green;
  border: 2px solid black;
  -webkit-mask: 
     radial-gradient( circle at center top,    transparent 30px, black 31px), 
     radial-gradient( circle at center bottom, transparent 30px, black 31px),
     linear-gradient(black,black); /* this layer is mandatory */
   -webkit-mask-composite: destination-in;
   mask-composite: exclude; /* for non-webkit browser */
}
<div></div>

Related