How to Mask by CSS
Posted By : Deepak Insa | 26-Nov-2014
Now you can mask a HTML element by CSS. For this an image shape is required in which you want to mask. Then apply CSS Property named -webkit-mask-image,e.g. -webkit-mask-image:url(image.png);.
Transparency of image is read by image mask and applied to the HTML element, like the picture shows below:-
You can shape an image as you want by Masking. Like :-
For this the HTML is:
<div class="example">
<p>Lorem ipsum dolor sit … Amet.(dummy text)</p>
</div>
And the CSS is:
.example {
width: 400px;
height: 300px;
overflow: hidden;
color: #fff;
background: desire-background;
-webkit-mask-image: url(desire-shape.png);
}
But this code works only in Chrome browser.
For mozilla and opera it's done by SVG, code written below:
<!DOCTYPE html>
<html>
<body>
<!-- SVG begins -->
<svg>
<!-- Definition of a mask begins -->
<defs>
<mask id="mask">
<image width="150px" height="150px" xlink:href="desire-shape.png"></image>
</mask>
</defs>
<!-- Definition of a mask ends -->
<foreignobject height="500px" style="mask: url(#mask);" width="500px">
<!-- HTML begins -->
<div class="element">
<p>Lorem ipsum dolor sit .. amet.</p>
</div>
<!-- HTML ends -->
</foreignobject>
</svg>
<!-- SVG ends -->
</body>
</html>
This is code for all modern browser, but some browser are does not support masking e.g. Internet Explorer etc.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Deepak Insa
Deepak is an experienced UI developer with experience and capabilities to build compelling UIs for Web and Mobile Applications.