从 css 中的容器 div 中减去一个洞

Subtract a hole from a container div in css

我有一个 DIV,我想从它的顶部中心减去一个洞,让它有点像名片夹的效果。这个洞需要让主体 DIV 后面的任何东西都能显示出来。

这张图片突出了这个想法。有什么想法吗?

这可以使用 CSS clip-path 函数来实现。

Here's an example of how to use clip-path (with an approximate shape).

Here are the MDN docs on clip-path.

我一般用Clippy or Boxy SVG来设计clip-path的形状。

如果您需要使用 clip-path 向元素添加 box-shadow,请改用 you'll have to use filter: drop-shadow(...);

更新: Here is a working example.

body {
  font-family: sans-serif;
}

#app {
  background: teal;
}

#card {
  position: relative;
  background: red;
  padding: 100px;
  width: 200px;
  height: 400px;
  clip-path: path( "M 93.385 67.118 L 179.825 67.118 C 179.825 67.13 179.825 67.142 179.825 67.154 C 179.825 81.302 191.295 92.772 205.443 92.772 C 219.591 92.772 231.061 81.302 231.061 67.154 C 231.061 67.142 231.061 67.13 231.061 67.118 L 321.217 67.118 C 331.461 67.118 339.766 75.423 339.766 85.667 L 339.766 284.691 C 339.766 294.935 331.461 303.24 321.217 303.24 L 94.385 303.24 C 84.141 303.24 75.836 294.935 75.836 284.691 L 75.836 85.667 C 75.836 75.423 84.141 67.118 94.385 67.118 Z");
}

#bg {
  background: orange;
  padding: 50px;
  position: absolute;
}
<div id="bg">
  <p>This is the background behind the card</p>
</div>
<div id="card">
  <h1>Hello Vanilla!</h1>
  <div>
    We use the same configuration as Parcel to bundle this sandbox, you can find more info about Parcel
    <a href="https://parceljs.org" target="_blank" rel="noopener noreferrer">here</a>.
  </div>
</div>

更新二: Here is another working example with elements visible behind the card