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>
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%;
}
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
}
But what happens if our surface has say a gradient background?
So can we solve this by adding the same gradient to the 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
}
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)