如何使用CSS制作自定义图标 无需第三方库及图片资源
纯CSS实现无依赖自定义图标方案
通用基类定义
首先先定义统一的图标基础样式,实现和Font Awesome一致的适配能力:
[class^="icon-"], [class*=" icon-"] { display: inline-block; width: 1em; height: 1em; font-size: inherit; line-height: 1; vertical-align: -0.125em; position: relative; color: currentColor; }
核心使用
currentColor继承父级文字颜色,em单位实现跟随文字大小自动缩放。
实现方案
1. 伪元素+基础形状拼接
通过before/after两个伪元素配合基础的矩形、圆形、边框样式拼接成图标,兼容性最好,适配全场景:
示例:搜索图标
/* 搜索图标 */ .icon-search::before { content: ''; position: absolute; top: 0; left: 0; width: 0.6em; height: 0.6em; border: 0.125em solid currentColor; border-radius: 50%; } .icon-search::after { content: ''; position: absolute; right: 0; bottom: 0; width: 0.125em; height: 0.4em; background-color: currentColor; transform: rotate(-45deg); transform-origin: top center; }
2. Border技巧实现几何形状
利用border的透明边特性可以快速生成三角形、箭头、气泡尖角等特殊形状,代码量极小:
示例:向下箭头图标
.icon-arrow-down::before { content: ''; position: absolute; top: 0.25em; left: 0.125em; width: 0; height: 0; border: 0.375em solid transparent; border-top-color: currentColor; }
3. clip-path裁剪自定义矢量形状
通过clip-path的polygon、path属性可以裁剪出任意自定义矢量形状,适合复杂图标,无需多元素拼接:
示例:五角星图标
.icon-star { background-color: currentColor; clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%); }
4. CSS渐变绘制复杂图标
组合linear-gradient、radial-gradient多层渐变可以绘制出层次丰富的复杂图标,所有效果都在单个元素上实现:
示例:首页房子图标
.icon-home { background: linear-gradient(currentColor, currentColor) 50% 70% / 20% 30% no-repeat, linear-gradient(currentColor, currentColor) 30% 70% / 20% 30% no-repeat, linear-gradient(currentColor, currentColor) 70% 70% / 20% 30% no-repeat, linear-gradient(to bottom right, transparent 45%, currentColor 45%, currentColor 55%, transparent 55%) 0 100% / 60% 60% no-repeat, linear-gradient(to bottom left, transparent 45%, currentColor 45%, currentColor 55%, transparent 55%) 100% 100% / 60% 60% no-repeat; }
使用说明
- 图标使用方式和Font Awesome完全一致,直接给标签加对应的class即可:
<i class="icon-search"></i> - 修改父元素的
color属性即可修改图标颜色,修改父元素的font-size属性即可修改图标大小 - 需要添加旋转、翻转等效果时,直接给图标元素加
transform相关CSS属性即可
内容的提问来源于stack exchange,提问作者Devs
相关产品推荐
相关产品推荐

