css - 以百分比 (%) 和像素 (px) 或 em 表示的边界半径

标签 css css-shapes

如果我使用像素或em值作为border-radius,边缘半径总是圆弧药丸形状甚至如果该值大于元素的最大边。

当我使用百分比时,边缘半径是椭圆形的,从元素每边的中间开始,形成卵形或椭圆形:

pixel (px) border radius percent (%) border-radius

边界半径的像素值:

div {
   background: teal;
   border-radius: 999px;
   width: 230px;
   height: 100px;
   padding: 40px 10px;
   box-sizing: border-box;
   font-family: courier;
   color: #fff;
 }
<div>border-radius:999px;</div>

边界半径的百分比值:

div {
  background: teal;
  border-radius: 50%;
  width: 230px;
  height: 100px;
  padding:40px 10px;
  box-sizing:border-box;
  font-family:courier;
  color:#fff;
}
<div>border-radius:50%;</div>

为什么以百分比表示的边界半径与使用像素或 em 值设置的边界半径的作用不同?

最佳答案

边界半径:

首先,您需要了解 border-radius 属性有两个值。这些值是定义 Angular 形状的四分之一椭圆的 X/Y 轴上的半径。
如果只设置了其中一个值,则第二个值等于第一个值。
所以 border-radius: x; 等同于 border-radius: x/x;

百分比值

引用 W3C 规范:CSS Backgrounds and Borders Module Level 3 border-radius property这是我们可以阅读的有关百分比值的内容:

Percentages: Refer to corresponding dimension of the border box.

所以 border-radius: 50%; 以这种方式定义椭圆的半径:

  • X 轴 上的半径是容器宽度
  • 的 50%
  • Y 轴 上的半径是容器高度
  • 的 50%

Border-radius in percentage (%) make an ellipsis

像素和其他单位

使用一个值而不是边框​​半径的百分比(em、in、视口(viewport)相关单位、cm...)将始终产生具有相同 X/Y 半径的椭圆。 换句话说,一个圆圈

当你设置 border-radius: 999px; 时,圆的半径应该是 999px。 但是另一个rule is applied when the curves overlap将圆的半径减小到最小边的一半。因此,在您的示例中,它等于元素高度的一半:50px。

Border-radius in pixels (px) make a pill shape


对于此示例(具有固定大小的元素),您可以使用 px 和百分比获得相同的结果。由于元素是 230px x 100pxborder-radius: 50%; 等价于 border-radius: 115px/50px; (50%双方):

.percent {
  border-radius: 50%;
}
.pixels {
  border-radius: 115px/50px;
}

/* For the demo : */
div {
  display: inline-block;
  background: teal;
  width: 230px;
  height: 100px;
  padding: 40px 10px;
  box-sizing: border-box;
  font-family: courier;
  font-size: 0.8em;
  color: #fff;
  text-align: center;
}
<div class="percent">border-radius: 50%;</div>
<div class="pixels">border-radius: 115px/50px;</div>

关于css - 以百分比 (%) 和像素 (px) 或 em 表示的边界半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29966499/

相关文章:

html - 如何为容器添加边框,中间有透明间隙

css - 有两条切边的矩形

html - <p> 标签中单词之间的文本间距不一样

c# - 如何将两个表格放在一起?

html - 固定标题隐藏在 JQuery Steps 页面上(仅在某些移动浏览器上)

html - 我如何创建背景为矩形的六边形?

三 Angular 形箭头的CSS渐变

css - 使用 Pure 居中表单

html - 模态行为异常

css - 使用 CSS 绘制顶部边框提示