Arms crossed picture of James Auble
example of diamond image using css image mask

Use Image Mask to Create Diamond Image With CSS Mask-Image

Published

So I found myself building out a section for a client's site that had a diamond shaped image instead of the more common rectangle. At first I thought to just use border radius on a rectangle and rotate the image by 45 degrees, but this created some unpredictable layout shift and quickly became apparent that this way might not be ideal.

You might be thinking "Hey, why not just have the user upload a diamond rendered image." Well, aside from the image either needing to have the appropriate background color baked into the image, or the image having an alpha channel--so needing a larger PNG rendered, that method requires designer intervention or at least someone savvy enough with image editing software. Wow, that was a long sentence! But you get the idea.

Luckily, I remembered using clip-path with SVG's which I made an earlier blog post about, and figured I could use CSS to achieve this.

Welcome in mask-image and -webkit-mask-image.

With these, we can simply reference an SVG image of whatever shape, through which our image will be visible.

TL;DR

Create our Diamond SVG 

Use your favorite vector image editing software such as Adobe Illustrator or Affinity Designer software to create the desired diamond shape (or whatever shape you want).

If you'd like to just use the diamond SVG I created you can download it here.

We're not going to inline this SVG file, so make sure you have it uploaded somewhere public.

Use CSS to Mask Our Image 

Now apply the -mask-image and -webkit-mask-image (for slightly more browser support) to our main image and use the URL for our diamond SVG as the value like so:

.our-image {
  -webkit-mask-image: url(https://a-path-to-our-svg-image.svg);
  mask-image: url(https://a-path-to-our-svg-image.svg);
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}

You might also want to define the focal point with the object-position and/or object-fit CSS properties.

Conclusion 

Voila! Now we have a diamond shaped image that will retain its shape no matter what our users upload.

Thanks for reading and code on web assassins!

Need a web developer?

Contact Me
Back to Blog
Scrolldown Icon