前面的话
之前了解过border-radius属性,最近写demo时原理又模糊了,这篇文章
来深究一下border-radius这个属性。
基本用法
要想得到一个圆,首先得有一个正方形,这里有一个边为100px的正方形,加上border-radius:50px ,就变成了一个圆。那么为什么要是50px呢?
<div class="demo"></div>
.demo {
width: 100px;
height: 100px;
background-color: red;
border-radius: 50px;
}
我们来看看控制台怎么显示的这个属性:
可以看到,显示了4个属性,我们可以联想到类似的属性。
例如:margin(margin-left、margin-top、margin-right、margin-bottom)
padding(padding-left,padding-top,padding-right,padding-bottom)
对于margin和padding,我们都知道它们的顺序是上右下左。设置一个值、多个值对应的是什么,我们都一清二楚。
那么 border-radius它的顺序又是怎样的呢?
回答是 左上、右上、右下、左下。
所以我们设置border-radius: 50px相当于border-radius:50px 50px 50px 50px
知道了border-radius这个属性可以分为4个属性:
border-top-left-radius
border-top-right-radius
border-bottom-left-radius
border-bottom-right-radius
之后,我们可想而知,上面的圆是由4部分组成,那修改一下参数会发生什么?
.demo2 {
width: 100px;
height: 100px;
background-color: red;
border-radius: 50px 0 0 0;
}
这么写相当于:border-top-left-radius:50px
(绿色部分为标记)
通过这张图我们看到的这个圆角:其实是:以左上角为起点,以水平50px,垂直50px的点为圆心, 50px为半径画的圆。
border-radius: 0 50px 0 0 相当于border-top-right-radius: 50px
这个是:以右上角为起点,以水平50px,垂直50px的点为圆心,50px为半径画圆的。
所以,上面的整圆不是直接画出来的,不是一个圆心,是四个圆心画出的四个圆与原来的div对应方向重叠形成的圆。
最大值
接下来看看,属性值能不能是负值呢?最大值又是多少?含义是什么?
1:能为负值吗?
当设置为负值时,控制台样式报错:
说明是不能设置为负值的,原因是;圆的半径是没有负值的。
2:最大值多少?
设置为100px,刚好为一边长:
border-top-left-radius:100px;
结果:
设置为200px:
border-top-left-radius:200px;
结果:
没有变化,说明:圆的半径最大为div的边长。
那么div不是正方形,是长方形又是如何呢?
.demo3 {
width: 200px;
height: 100px;
background-color: red;
border-top-left-radius: 200px 100px;
}
这是一个宽200px,高100px的长方形。圆角半径为200px,与宽相同,是高的两倍,看一下结果:
是一个宽高100px的圆。
如果想得到一个椭圆,怎么实现呢?
其实着4个分开的属性可以设置两个值:border-top-radius: x y;
x,y分别为x偏移量与y偏移量,有了这个偏移量就可以实现椭圆了。
border-top-radius: 200px 100px;
总结一下:
-
当使用一个值时,宽高一致,当宽高其中任意值超过宽高的最小值。则默认选择其中最小的值。
-
当使用两个值时,就不一样了:看一个例子
.demo4{
width:100px;
height:100px;
background-color:#f00;
border-top-left-radius:2000px 100px;
}
结果:
当分开写时,最大值超过宽高最大值时,会按照宽高最大值等比缩放
2000 : 100 => 200 : 10
看一下200 : 10的情况:
结果是一样的。
高级写法
最后说一下border-radius高级写法
我们可以明确声明每个角的x,y是这样的:
border-top-left-radius:10px 20px;
border-top-right-radius:10px 20px;
border-bottom-right-radius:10px 20px;
border-bottom-left-radius:10px2 0px;
这里有一种更简单的表达形式:
border-radius:10px/20px;
border-radius:10px 10px 10px 10px/ 20px 20px 20px 20px;
等同于上面的写法,就是把x和y的值,分别写出来,用/分开。
含义
我们border-radius:后面两个值,和三个值的含义。
[两个值]
当border-radius参数为两个值时(x,y)代表含义是
-
左上,右下:x
-
右上,左下:y
[三个值]
当border-radius参数为两个值时(x,y, z)代表含义是:
-
左上:x
-
右上,左下:y
-
右下:z