首页 > 解决方案 > clip-path svg 适用于图像,但不适用于 div

问题描述

在 MDN 上有一个关于如何在图像上使用剪辑路径 svg 的示例。相同的剪辑路径似乎不适用于div元素。有人可以澄清一下:

剪切图像的示例代码(基于 MDN 文档)

#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>

div 上的相同剪辑路径(似乎不起作用)

#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>

标签: csssvgclip-path

解决方案


解决您的问题的方法是使用clipPathUnits="objectBoundingBox"并构建大小在 0 和 1 之间的剪切路径,如下所示:

#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>


推荐阅读