在前端开发中,使用CSS3绘制基本图形可以减少图片资源的加载,提升页面性能,同时方便后续调整样式。下面介绍11种常见基本图形的实现代码。
1. 圆形
通过border-radius属性设置50%即可实现圆形。
.circle {
width: 100px;
height: 100px;
background-color: #409eff;
border-radius: 50%;
}
2. 椭圆形
分别设置水平方向和垂直方向的border-radius为50%即可。
.ellipse {
width: 150px;
height: 100px;
background-color: #67c23a;
border-radius: 50% / 50%;
}
3. 正方形
设置宽高相等的矩形就是正方形。
.square {
width: 100px;
height: 100px;
background-color: #e6a23c;
}
4. 矩形
设置不同的宽高即可实现矩形。
.rectangle {
width: 150px;
height: 100px;
background-color: #f56c6c;
}
5. 向上三角形
利用边框的透明属性实现三角形效果。
.triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid #909399;
}
6. 向下三角形
调整边框的方向即可实现向下的三角形。
.triangle-down {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 100px solid #409eff;
}
7. 向左三角形
将边框的透明方向调整到上下,右侧设置颜色即可。
.triangle-left {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-right: 100px solid #67c23a;
}
8. 向右三角形
左侧边框设置颜色,其余方向透明即可。
.triangle-right {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-bottom: 50px solid transparent;
border-left: 100px solid #e6a23c;
}
9. 梯形
在三角形的基础上设置宽度,即可形成梯形效果。
.trapezoid {
width: 100px;
height: 0;
border-left: 30px solid transparent;
border-right: 30px solid transparent;
border-bottom: 100px solid #f56c6c;
}
10. 平行四边形
使用transform的skew属性倾斜矩形即可。
.parallelogram {
width: 150px;
height: 100px;
background-color: #909399;
transform: skew(-20deg);
}
11. 五角星
通过两个三角形叠加组合实现五角星效果。
.star {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 70px solid #409eff;
position: relative;
}
.star::after {
content: '';
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 70px solid #409eff;
position: absolute;
top: 20px;
left: -50px;
}