css 制作icon
使用CSS制作图标的方法
使用伪元素和边框
通过CSS的::before或::after伪元素结合边框属性可以创建简单图标。例如制作一个三角形图标:
.triangle {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 20px solid #333;
}
利用transform旋转
通过旋转矩形或正方形可以创建更多形状。例如制作一个加号图标:
.plus {
width: 20px;
height: 2px;
background: #000;
position: relative;
}
.plus::after {
content: '';
width: 2px;
height: 20px;
background: #000;
position: absolute;
left: 9px;
top: -9px;
}
使用box-shadow
通过box-shadow属性可以创建复杂图案。例如制作一个搜索图标:
.search {
width: 16px;
height: 16px;
border: 2px solid #000;
border-radius: 50%;
position: relative;
}
.search::after {
content: '';
width: 2px;
height: 8px;
background: #000;
position: absolute;
bottom: -5px;
right: -5px;
transform: rotate(45deg);
}
使用clip-path
clip-path属性可以创建更复杂的形状。例如制作一个五角星:
.star {
width: 0;
height: 0;
color: gold;
position: relative;
display: block;
border-right: 10px solid transparent;
border-bottom: 7px solid currentColor;
border-left: 10px solid transparent;
transform: rotate(35deg);
}
.star::before {
content: '';
width: 0;
height: 0;
border-right: 10px solid transparent;
border-bottom: 7px solid currentColor;
border-left: 10px solid transparent;
position: absolute;
top: -4.5px;
left: -10.5px;
transform: rotate(-70deg);
}
使用SVG背景
将SVG代码直接嵌入CSS中作为背景:
.heart {
width: 20px;
height: 20px;
background: url("data:image/svg+xml,%3Csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z' fill='%23ff0000'/%3E%3C/svg%3E") no-repeat center;
background-size: contain;
}
注意事项
- 纯CSS图标适合简单图形,复杂图标建议使用SVG
- 考虑使用CSS变量便于主题切换
- 移动端注意点击区域大小
- 高对比度模式下测试显示效果
这些方法可以根据项目需求灵活组合使用,实现各种常见的UI图标效果。
![]()






