Search code examples
csssvgclip

SVG clipping path is positioned incorrectly when referenced as css clip-path property


I set up this code pen: http://codepen.io/jasonpearson/pen/pjKwBZ

When you uncomment the -webkit-clip-path property, you can see the mask is smaller and not centered like it is when applied to the SVG. How can I adjust so the clipping mask shows up the same when applied using css or svg?

<style>
  * {
    padding: 0;
    margin: 0;
  }

  svg {
    border: 1px dotted black;
  }

  #myDiv {
    background: blue;
    max-width: 500px;
    //-webkit-clip-path: url('/#myClipPath')
  }
</style>

<div id="myDiv">
    <svg viewBox="0 0 100 100">
    <defs>
      <clipPath id="myClipPath">
        <circle cx="50" cy="50" r="30"/>
      </clipPath>
    </defs>

    <rect x="0" y="0" height="100" width="100" fill="yellow" clip-path="url(#myClipPath)" />
  </svg>  
</div>

Solution

  • You can switch the clipPath to using coordinates based on the objectBoundingBox, instead of absolute coordinates.

      * {
        padding: 0;
        margin: 0;
      }
    
      svg {
        border: 1px dotted black;
      }
    
      #myDiv {
        background: blue;
        max-width: 500px;
        -webkit-clip-path: url('/#myClipPath')
      }
    <div id="myDiv">
        <svg viewBox="0 0 100 100">
        <defs>
          <clipPath id="myClipPath" clipPathUnits="objectBoundingBox">
            <circle cx="0.5" cy="0.5" r="0.3"/>
          </clipPath>
        </defs>
    
        <rect x="0" y="0" height="100" width="100" fill="yellow" clip-path="url(#myClipPath)" />
      </svg>  
    </div>