Search code examples
csssvgclip-path

clip-path svg works on image, but not on div


On MDN there is an example on how to use a clip-path svg on an image. The same clip-path does not seem to apply on a div element. Can someone clarify:

  • Why this code does not work as intended
  • A way to make an svg clip-path work on a div

Example code (based on MDN docs) clipping an image

#clipped {
  clip-path: url(#cross);
}
<img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg"
    alt="MDN logo">
<svg height="0" width="0">
  <defs>
    <clipPath id="cross">
      <rect y="110" x="137" width="90" height="90"/>
      <rect x="0" y="110" width="90" height="90"/>
      <rect x="137" y="0" width="90" height="90"/>
      <rect x="0" y="0" width="90" height="90"/>
    </clipPath>
  </defs>
</svg>

The same clip-path on a div (which does not seem to work)

#clipped {
  width: 100px;
  height: 100px;
  background: black;
  clip-path: url(#cross);
}
<div id="clipped"></div>
<svg height="0" width="0">
  <defs>
    <clipPath id="cross">
      <rect y="110" x="137" width="90" height="90"/>
      <rect x="0" y="110" width="90" height="90"/>
      <rect x="137" y="0" width="90" height="90"/>
      <rect x="0" y="0" width="90" height="90"/>
    </clipPath>
  </defs>
</svg>


Solution

  • A solution to your problem would be using clipPathUnits="objectBoundingBox" and build the clipping path with sizes between 0 and 1 like so:

    #clipped {
      margin:1em;
      width: 100px;
      height: 100px;
      background: black;
      display:inline-block;
      clip-path: url(#cross);
    }
    #clipped.big{
      width: 200px;
      height: 200px;
    }
    <div id="clipped"></div>
    <div id="clipped" class="big"></div>
    <svg viewBox="0 0 1 1">
      
        <clipPath id="cross" clipPathUnits="objectBoundingBox">
           <rect y="0" x="0" width=".4" height=".4"/>
           <rect y="0.6" x="0" width=".4" height=".4"/>
           <rect y="0" x="0.6" width=".4" height=".4"/>
           <rect y="0.6" x="0.6" width=".4" height=".4"/>
        </clipPath>
      
    </svg>