Search code examples
csssvgclippingclip-path

Transform CSS clip-path with mixed (fixed and percentage) values to SVG clip-path


I have a card image with gradient with clipped corner using clip-path:

.card {
  width: 200px;
  height: 200px;
  background: linear-gradient(to bottom, blue, green);
  clip-path: polygon(20px 0, 100% 0, 100% 100%, 0 100%, 0 20px);
}
<div class="card"></div>

Clipped corner must have fixed size regardless of card size so I'm using pixels for clipping corner.

But clip-path has not the best browser support at the moment, so I've tried converting this HTML and CSS to SVG.

.container {
  width: 200px;
  height: 200px;
}
<div class="container">
  <svg viewBox="0 0 100 100" clip-path="url(#myClip)">
    <defs>
      <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
        <stop offset="100%" style="stop-color:rgb(0,255,0);stop-opacity:1" />
      </linearGradient>
    </defs>
  
    <polygon points="20,0 100,0 100,100 0,100 0,20" fill="url(#grad1)" />
 </svg>
</div>

But the issue is that I can't make this clipped corner to have fixed size regardless of card size.


Solution

  • With the help from Stack Overflow in Russian using SVG mask my solution is this

    .container {
      width: 200px;
      height: 200px;
    }
    
    svg {
      width: 100%;
      height: 100%;
    }
    <div class="container">
      <svg>
        <defs>
          <mask id="triangle-clip">
            <rect x="0" y="0" width="100%" height="100%" fill="#fff" />
            <path d="M0,20 v-20 h20 z" fill="#000" />
          </mask>
    
        <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
          <stop offset="100%" style="stop-color:rgb(0,255,0);stop-opacity:1" />
        </linearGradient>
      </defs>
      <rect width="100%" height="100%" fill="url(#grad1)" mask="url(#triangle-clip)" />
    </svg>
    </div>