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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay