Using Border-radius CSS for rectangular divs produces elliptical corners instead of rounded corners. How can I get perfect rounded corners for rectangular divs?
(source: mozilla.org)
Formally, the syntax for the border-radius property accepts 2 values for each corner: a horizontal radius and a vertical radius (separated by a slash). The following line would create an elliptical border-radius similar to the third image above.
border-radius: 10px / 5px;
Usually, we only specify one value. In this case, that value gets used as both the vertical and horizontal radii. The following line would create a circular border-radius similar to the second image above.
border-radius: 10px;
Using Percentages
The Mozilla Developer's Network defines the possible value types for this property as follows:
<length>
Denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipsis. It can be expressed in any unit allowed by the CSS data types. Negative values are invalid.<percentage>
Denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipsis, using percentage values. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid.
Using a single value to create a circular radius is fine when we're using absolute length
units like pixels or ems, but gets more complicated when we're using percentages. Since the single-value usage of this property is synonymous with using the same value twice, the following two lines are equivalent; however, these would not necessarily create a circular border-radius.
border-radius: 50%;
border-radius: 50%/50%;
These lines say the border is defined by an ellipse whose vertical radius is equal to 50% of the element's height and whose horizontal radius is equal to 50% of the element's width. If the element is 200 pixels wide and 100 pixels tall, this results in an ellipse rather than a circle.
Solution
If you want a circular border-radius, the easiest thing to do is to use absolute measurement units (like pixels or ems or anything besides percentage), but sometimes that doesn't fit your use case and you want to use percentages. If you know the aspect-ratio of the containing element, you still can! In the example below, since my element is twice as wide as it is tall, I've scaled the horizontal radius in half.
#rect {
width: 200px;
height: 100px;
background: #000;
border-radius: 25%/50%;
}
<div id="rect"></div>
Another option is to provide a sufficiently huge value in any absolute measurement unit. If the value exceeds half of the shortest side's length, the browser will use the minimum as its border-radius in both directions, producing a perfect pill shape on rectangular elements.
#rect {
width: 200px;
height: 100px;
background: #000;
border-radius: 100vmax;
}
<div id="rect"></div>