This page explains how to draw a circle in a square in CSS. A famous example of application is the move selection on chess.com:
The circle is added with the CSS selector ::before
, but should also work the same way with ::after
.
Let's considere the following HTML code. The code contains two divs with the class square
.
The second div also have the class with-circle
that add a circle in the square.
<div class="square"></div>
<div class="square with-circle"></div>
The .square
class set the div dimensions and colors to create the square:
.square {
background-color: #6297CB;
border: 3px solid #468189;
width: 30vmin;
height: 30vmin;
margin: 5px;
}
When the element also have the .with-circle
class, we add the circle inside the square with the following CSS:
.square.with-circle::before{
content: '';
display: inline-block;
left: 20%;
top: 20%;
width: 60%;
height: 60%;
border-radius: 100%;
background-color: #00CC66;
position: relative;
}
The selector is .square.with-circle
that selects elements with both classes .square
and .with-circle
.
We add the ::before
to create a new element before the square.
The ::before
element must have a content and is aligned inline with the square:
content: '';
display: inline-block;
We set the circle as 60% of the square:
width: 60%;
height: 60%;
The trick to center the circle is to move the circle 20% from the left (20% on the left + 60% width circle + 20% on the right = 100% opf the square).
To set the position of the circle with the left
property, we must specify that the circle position is relative to the square:
position: relative;
left: 20%;
top: 20%;
Finally, to transform the element into circle, we add the following border-radius
property:
border-radius: 100%;
Here is the result: