CSS does not draw a circle with fixed width and height
CSS Draw a Circle Without a Fixed Width and Height
In this article, we’ll show you how to use CSS to draw a circle without using a fixed width and height.
Read more: CSS Tutorial
Drawing a Circle with Padding
We can use the padding property to create a circle without a fixed width or height. First, create a div element in HTML and give it a class name, such as “circle.” Then, in CSS, use border-radius to transform it into a circle. Within this class’s style, set the padding-bottom and padding-left properties to the same percentage to create a perfect circle. Here is a code example:
<div class="circle"></div>
.circle {
width: 0;
height: 0;
padding-bottom: 50%;
padding-left: 50%;
background-color: red;
border-radius: 50%;
}
In the code above, both padding-bottom and padding-left are set to 50%, making the width and height of the div element 50% of the parent element’s width. Because the border-radius is set to 50%, the div element appears circular. You can adjust the padding percentage to adjust the size of the circle as needed.
Drawing a Circle Using Pseudo-Elements
In addition to using padding, we can also use the ::before or ::after pseudo-elements to create a circle with a fixed width and height. We can do this by making the pseudo-element a square, setting the border-radius property to 50%, and then using the transform property to scale it into a circle. Here is a code example:
<div class="circle"></div>
.circle {
position: relative;
width: 50%;
padding-top: 50%;
}
.circle::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
padding-bottom: 100%;
background-color: blue;
border-radius: 50%;
transform: scale(1, 1);
}
In the code above, we first set the width and padding-top percentages of a div element to render it as a square. Then, we use the ::before pseudo-element to create a square of the same size and transform it into a circle by adjusting the padding-bottom percentage. Finally, we scale it to form a circle using the scale parameter of transform. You can adjust the percentage values of the div element and pseudo-element to change the size of the circle as needed.
Drawing a Circle with SVG
Another way to draw a circle without a fixed width and height is to use SVG (Scalable Vector Graphics). SVG is an XML-based vector graphics format that can be scaled without distortion. We can use the
<svg class="circle">
<circle cx="50%" cy="50%" r="50%" fill="yellow" />
</svg>
.circle {
width: 50%;
padding-top: 50%;
}
In the code above, we first set the width and padding-top percentages of an
Summary
In this article, we’ve introduced three methods for drawing a circle with a fixed width and height using CSS. By using the padding property, the ::before and ::after pseudo-elements, and SVG, we can easily create circles of varying sizes. You can choose the method that best suits your needs. We hope you’ve found this article helpful!