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

 

About Author

Author Image
Deepak Insa

Deepak is an experienced UI developer with experience and capabilities to build compelling UIs for Web and Mobile Applications.

Request for Proposal

Name is required

Comment is required

Sending message..