Search code examples
csssvgclip-path

Complex SVG clip-path responsive


I'm trying to take a complex path shape and apply it as a clip-path mask in css, but I can't figure out how to get the clip mask to "fill" the parent container. Rather it just gets cut off or doesn't expand to fill the available space.

If I add clipPathUnits="objectBoundingBox" it doesn't appear at all.

<svg viewBox="0 0 720 720">
  <defs>
    <clipPath id="map">
      <path d="M568.421 326.842L511.579 270v37.895h-18.947v-18.948h-56.843v37.895l18.948 37.894v18.948h-18.948l37.896 56.842h-37.896l-18.947-18.948v-18.947h-37.895L360 383.684h-18.947l-18.948-37.894v-37.895L360 270l37.895-37.895-18.948-37.895H360v18.948l-18.947-18.948h-18.948v37.895h-37.894l-56.843-18.947-37.894-56.842h-56.842l-18.947-18.948-75.79 75.79v37.895h18.947v75.789L37.895 345.79l5.532 48.163 32.362 46.573 113.685 37.895 94.737 18.947h94.736v-18.947h37.895l18.947 37.895h18.948v56.842l56.842-37.894v-37.896h37.895l18.947-37.894v-37.896l56.842-37.894V345.79l-18.948-18.948z"/><path d="M246.315 194.21h56.843v-18.947l-18.947-37.895h-18.948v37.895h-18.948zM227.368 137.368h18.947v-18.947h-37.894V156.316h18.947zM341.053 175.263h56.842l37.894 37.895-18.947 18.947V270h75.79v-18.947h-37.895v-18.948h37.895V194.21h-37.895l-56.842-56.842h-56.842zM265.263 99.474h18.948v18.947h-18.948zM284.211 61.579h18.947v18.948h-18.947zM303.158 108.947h18.947v18.947h-18.947zM341.053 99.474h37.895v18.947h-37.895zM227.368 80.526h18.947v18.947h-18.947zM378.947 80.526V4.737H360l-37.895 37.894v18.948l18.948 18.947zM587.368 440.526h37.895v37.895h-37.895zM663.158 364.736V345.79h-18.947V402.631l56.842-18.947v-18.948zM378.947 270h18.947v18.947h-18.947zM644.211 421.578h18.947v18.948h-18.947zM644.211 459.474h18.947v18.947h-18.947z"/>
    </clipPath>
  </defs>
</svg>

https://codepen.io/picard102/pen/aEwJzR


Solution

  • As Robert said, when you specify clipPathUnits="objectBoundingBox", the coordinates in the clip path definition are supposed to be between 0,0 (the top left) and 1,1 (the bottom right).

    Your paths are about 700x575, so your path is about 600 to 700 times too big.

    The simplest solution is to add a transform attribute to your <clipPath> that scales the coordinates down to the correct range.

    <clipPath id="map" clipPathUnits="objectBoundingBox" transform="scale(0.00143, 0.00174)">
    
    • 1/700 ~= 0.00143
    • 1/575 ~= 0.00174

    https://codepen.io/anon/pen/GyvZOM