Search code examples
htmlcssclip

Subtract a hole from a container div in css


I have a DIV that I'm trying to subtract a hole from the top center of, giving it a kinda card holder effect. The hole needs to allow whatever is behind the main DIV to show through.

This image highlights the idea. Any ideas?

enter image description here


Solution

  • This can be achieved using the CSS clip-path function.

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

    Here are the MDN docs on clip-path.

    I generally use Clippy or Boxy SVG for designing the clip-path shape.

    If you need to add a box-shadow to an element using clip-path, you'll have to use filter: drop-shadow(...); instead.

    Update: 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>

    Update 2: Here is another working example with elements visible behind the card