前言
最近在看各大厂的面试题时发现大多数都在考察css基础时都喜欢让面试者用纯CSS实现三角形、圆形等各种图形,因此写下这篇笔记记录一下
纯CSS实现三角形
border
先来看看当宽高为0,border宽度为50px的图形是什么样的
<div class="triangle"></div>
.triangle {
width: 0px;
height: 0px;
border-top: 50px solid red;
border-right: 50px solid green;
border-bottom: 50px solid blue;
border-left: 50px solid yellow;
}
这样一来,我们就可以将其他三边的颜色设为transparent,即可留下底下的三角形了
.triangle {
width: 0;
height: 0;
border-bottom: 50px solid #565656;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
}
clip-path剪裁
clip-path属性使用裁剪方式创建元素的可显示区域。区域内的部分显示,区域外的隐藏。
clip-path的语法有四种:
- inset(定义矩形)
- circle(定义圆)
- ellipse(定义椭圆)
- polygon(定义多边形) polygon的值为多个坐标点组成,坐标第一个值是x方向,第二个值是y方向。左上角是原点,右下角是(100%,100%)的点
.triangle {
width: 100px;
height: 100px;
background: cyan;
clip-path: polygon(0 100%, 50% 0, 100% 100%); // 对应三角形三个顶点
}
纯CSS实现圆角三角形
先画出一个圆角border,通过旋转扭曲将它变成圆角三角形头部,再利用伪元素旋转变换成为三角形两个底角
<div class="rounded-triangle"></div>
.rounded-triangle {
width: 50px;
height: 50px;
border-top-right-radius: 30%; // 圆角弧度
background: cyan;
transform: rotate(-60edg) skewX(-30edg) scale(1, .866)
}
.rounded-triangle:before,
.rounded-triangle:after {
content: '';
position: absolute;
background-color: inherit;
width: 50px;
height: 50px;
border-top-right-radius: 30%;
}
.rounded-triangle:before {
transform: rotate(-135deg) skewX(-45deg) scale(1.414, .707) translate(0,-50%);
}
.rounded-triangle:after {
transform: rotate(135deg) skewY(-45deg) scale(.707, 1.414) translate(50%);
}
纯CSS实现圆形
border-radius
border-radius实际上是border-top-left-radius、border-top-right-radius、border-bottom-right-radius、border-bottom-left-radius四个属性的简写模式,因此,border-radius : 30px;,其实等价于border-radius : 30px 30px 30px 30px;
那么我们可以用50%来作为border-radius的数值,产生的效果就是对象的长宽乘以数值得到垂直半径和水平半径
<div class="circle"></div>
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: cyan;
}
如果用
border-radius生成圆形的话,要确定div的宽高相等,如果不相等的话,画出来会是一个椭圆形
clip-path
使用clip-path的circle语法,circle的值由一个圆心和半径组成
.circle {
width: 100px;
height: 100px;
background: cyan;
clip-path: circle(50% at 50% 50%); /* 圆心(50% 50%) 半径50% */
}