1

I am looking for a way to create a square div of relative size, say, 70% x 70% with a background color and a circular hole in it (so that the background can be seen behind it) of the same size so that the sides of the div are tangent.

nwk
  • 4,004
  • 1
  • 21
  • 22
user2444319
  • 107
  • 1
  • 7

1 Answers1

12

You could use radial-gradient to achieve this.

html,
body {
  height: 100%;
  margin: 0;
  background: url(http://www.lorempixel.com/600/400) 100% 100%;
}
div {
  position: relative;
  width: 70%;
  height: 70%;
  background: -webkit-radial-gradient(50% 50%, circle, transparent 10%, #000 10%);
  background: -moz-radial-gradient(50% 50%, circle, transparent 10%, #000 10%);
  background: radial-gradient(50% 50%, circle, transparent 10%, #000 10%);
  margin: 0 auto;
}
<div></div>

Here's an svg approach.

body {
  background: url(http://www.lorempixel.com/600/400/);
  background-size: 100% 100%;
  margin: 0;
}
<svg viewBox="0 0 400 200" width="400" height="200">
  <path d="M0,0 L400,0 L400,200 L0,200z M200,100 m-50,0 a50,50 0 1,0 100,0 a50,50 0 1,0 -100,0z" fill="black" />
</svg>
Weafs.py
  • 22,731
  • 9
  • 56
  • 78
  • 3
    There are browsers which aren't gecko nor webkit browsers. Please inlude the standard syntax without vendor prefix for them. Moreover, latest versions of major browsers don't require any prefix. – Oriol Dec 19 '14 at 22:24
  • 1
    groovy looks great. real simple. I am getting a lot of jagged edges on the circle. Is there any way to fix this? thanks – user2444319 Dec 19 '14 at 22:42
  • @user2444319 - You could change it to `(50% 50%, circle, transparent 10%, #000 11%)` to smoothen the edges but Chrome still makes it look ugly. I'll add an alternate solution using `svg` to fix this issue. – Weafs.py Dec 19 '14 at 22:46
  • thanks im looking forward to it – user2444319 Dec 19 '14 at 22:50
  • I would suggest you add your svg approach in the original question as well as it isn't present there. – web-tiki Dec 20 '14 at 18:17
  • is it possible to have a rectangle or triangle instead of circle inside? – johannesMatevosyan Mar 24 '16 at 19:12
  • @chipChocolate.py thanks for the answer but could you be more precise, which one is d attribute? – johannesMatevosyan Mar 24 '16 at 19:32
  • 1
    @johannesMatevosyan - d attribute of the path element enclosed in svg tags. I'm sorry I'm on my phone right now, can't edit the code for you. – Weafs.py Mar 24 '16 at 19:35
  • 1
    @johannesMatevosyan - Anyway, here's the `d` attribute for rectangle - `"M0,0 L400,0 L400,200 L0,200z M200,100 m-50,0 v-25 h100 v50 h-100z"` and for triangle - `"M0,0 L400,0 L400,200 L0,200z M200,100 m0,-50 l35,100 h-70z"` – Weafs.py Mar 24 '16 at 19:56
  • the value of the standard un-prefixed `radial-gradient` marked as invalid in my latest Opera (chrome) inspector. – Taufik Nur Rahmanda Jun 24 '21 at 10:29