Using a div as a clipping mask in css

Paul Mckay picture Paul Mckay · Aug 14, 2013 · Viewed 16.9k times · Source

I have a background image that has background-size:cover; applied to it and then a series of divs overlaid which I would like to become individual clipping masks.

I've looked at the feature clip: rect(20px, 20px, 20px, 20px,); however as the divs are brought in through a CMS system, it will be inappropriate to define set sizes.

Is there a way of setting the div with a clipping mask property so that it clips the image anywhere the div is placed on the page?

I don't particularly want to use an image overlay either as this site will be responsive.

Answer

Tyblitz picture Tyblitz · Aug 14, 2013

If I understood correctly, you're simply looking for an overlay that will resize with the screen size, and the div with the background image?

In that case, if possible, why not simply append these divs INSIDE the div that needs clipping, like this. For this sample purpose I only used one div with a transparent background and a border applied to it. If you need to clip the image in a non-rectangular shape, you will need more divs (ex. for parallelogram, diamond, triangle shape, you'll need at least 2).

Also, sadly CSS doesn't allow for % borders, but I think this example is

You can also do it the other way around and place your img div inside the clipper divs; just a matter of what fits best...

body, html { 
  /* necessary for sizing children in % */
  width: 100%;
  height: 100%;
}
#tobeClipped {
  width: 80%;
  height: 40%;
  position: relative;
  background-image: url('http://cdn.theatlantic.com/static/infocus/ngpc112812/s_n01_nursingm.jpg');
  background-size: cover;
}
#tobeClipped>div {
  position: absolute;
}
#clippers {
  width: 100%;
  height: 100%;
  border: 20px solid grey;
  border-left-width: 100px;
  box-sizing: border-box;
}
<div id="tobeClipped">
    <div id="clippers"></div>
</div>

Please do clarify if this was not at all what you were looking for.