html - 避免在 CSS border-radius 中使用椭圆形

标签 html css

为矩形 div 使用 Border-radius CSS 会产生椭圆 Angular 而不是圆 Angular 。如何为矩形 div 获得完美的圆 Angular ?

最佳答案

image from MDN
(来源:mozilla.org)

形式上,border-radius 属性的语法为每个 Angular 接受 2 个值:水平半径和垂直半径(由斜线分隔)。以下行将创建一个类似于上面第三张图片的椭圆形边界半径。

border-radius: 10px / 5px;

通常,我们只指定一个值。在这种情况下,该值同时用作垂直和水平半径。以下行将创建类似于上面第二张图片的圆形边界半径。

border-radius: 10px;

使用百分比

Mozilla Developer's Network如下定义此属性的可能值类型:

<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.

当我们使用绝对 length 单位(如像素或 em)时,使用单个值创建圆半径很好,但当我们使用百分比时会变得更加复杂。由于此属性的单值用法等同于两次使用相同的值,因此以下两行是等效的;但是,这些不一定会创建圆形边界半径。

border-radius: 50%;
border-radius: 50%/50%;

这些行表示“创建一个椭圆或圆,其垂直半径等于元素高度的 50%,水平半径等于元素宽度的 50%,并将其用作边框半径。”。如果元素的宽度为 200 像素,高度为 100 像素,则会生成椭圆而不是圆形。


解决方案

如果你想要一个圆形的 border-radius,最简单的方法是使用绝对测量单位(如像素或 ems 或百分比以外的任何单位),但有时这不适合你的用例,你想使用百分比.如果您知道包含元素的纵横比,您仍然可以!在下面的示例中,由于我的元素的宽度是它的高度的两倍,所以我将水平半径缩放了一半。

#rect {
  width: 200px;
  height: 100px;
  background: #000;
  border-radius: 25%/50%;
}
<div id="rect"></div>

另一种选择是以像素或任何其他绝对测量单位提供足够大的值。如果该值超过最短边长度的一半,浏览器将在两个方向上使用最小值作为其边界半径,从而在矩形元素上产生完美的药丸形状。

#rect {
  width: 200px;
  height: 100px;
  background: #000;
  border-radius: 100000000000000px;
}
<div id="rect"></div>

关于html - 避免在 CSS border-radius 中使用椭圆形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31617136/

相关文章:

html - Bootstrap 4 中的表格列宽

html - 如何定位 <ul> 中的前四个 <li>

javascript - 从 Android 中执行 HTML 文件中的 Javascript

javascript - 为什么使用 "always allow"时 Firefox 中没有 `getUserMedia` 选项?

javascript - 使用 selenium 和 python 在文本框中快速写入

javascript - React获取div元素大小不正确

javascript - 面板内的 jQuery Accordion 对齐

javascript - 使用 BootstrapVue 的 VueJs Form textarea 和文本格式问题

html - 更改网址名称

c# - ViewModel 与 Model 有不同的字段吗?