DEV Community

Cover image for CSS: Punching Through the Surface
prodbyola
prodbyola

Posted on

CSS: Punching Through the Surface

While working on Cobhams Player, I needed to design a surface that gives an impression that it's been punched through. I expected the implementation of this effect to be quite straightforward in CSS. Turns out I was wrong for my use case. I ended up with my own implementation. However, I came across a certain CSS property which has proven useful in this regard: background-attachment. Let's see how it works.

<div class="container">
   <div class="surface">
       <div class="hole"></div>
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Our HTML code has a main container, a surface that we need to "punch through" and the hole we're punching. And here's our CSS code:

.container {
    padding: 28px;
    width: 100%;
}

.surface {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: black;
    width: 300px;
    height: 300px;
    margin: auto;
}

.hole {
    height: 150px;
    width: 150px;
    border-radius: 50%;
}
Enter fullscreen mode Exit fullscreen mode

CSS Hole

As you can see, our black surface is yet to show a hole, so let's make it happen. It's quite straightforward if our container's background has a plain color, say blue. We only need to add the same background to the hole:

.container {
    padding: 28px;
    width: 100%;
    background: blue; // <-- add this
}

.hole {
    height: 150px;
    width: 150px;
    border-radius: 50%;
    background: blue; // <-- add this
}
Enter fullscreen mode Exit fullscreen mode

CSS Hole

But what happens if our surface has say a gradient background?

CSS Hole

So can we solve this by adding the same gradient to the hole?

CSS Hole

Looks better right? But it doesn't really look much like a hole through to the background. This is where background-attachment: fixed; can be of help:

.hole {
    height: 150px;
    width: 150px;
    border-radius: 50%;
    background: linear-gradient(239deg,#de2134 27.11%,#38bf8e 73.91%);
    background-attachment: fixed; // <-- Add this
}
Enter fullscreen mode Exit fullscreen mode

CSS Hole

That's it. Now we've successfully created a hole that punches through.

Thank you for reading. Let me know what you think.

Top comments (0)