如果我使用像素或em值作为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%
像素和其他单位
使用一个值而不是边框半径的百分比(em、in、视口(viewport)相关单位、cm...)将始终产生具有相同 X/Y 半径的椭圆。 换句话说,一个圆圈。
当你设置 border-radius: 999px;
时,圆的半径应该是 999px。 但是另一个rule is applied when the curves overlap将圆的半径减小到最小边的一半。因此,在您的示例中,它等于元素高度的一半:50px。
对于此示例(具有固定大小的元素),您可以使用 px 和百分比获得相同的结果。由于元素是 230px x 100px
,border-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/