12

CSS 控制图标颜色

 3 years ago
source link: http://eux.baidu.com/blog/fe/%E6%8E%A7%E5%88%B6%E5%9B%BE%E6%A0%87%E9%A2%9C%E8%89%B2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

CSS 控制图标颜色

by.林枫2018-6-15

实际项目中,一般都会遇到不同颜色的图标,例如

alt
alt

导航栏图标的不同状态

需要UI设计师给出不同颜色的图标,在不同状态下设置不同的元素背景。

.icon {
    background-image: url(./home.png);
}

.icon.active {
    background-image: url(./home-active.png);
}

缺点是:当状态改变后,浏览器才去拉取active状态的图片,所以视觉上会有闪动,体验不好

将两张图标合成雪碧图

.icon {
    background-image: url(./sprite.png);
    background-position: 0 0;
}

.icon.active {
    background-image: url(./home-active.png);
    background-position: -20px -20px;
}

优点:解决第一个方法闪动的问题
缺点:1. 合成雪碧图需要工作量;2.多了个图标,增加雪碧图的体积

CSS3投影---filter:drop-shadow(color, X-offset, Y-offset)

color:投影的颜色
X-offset: X轴偏移量
Y-offset:Y轴偏移量

drop-shadow:就好像光线照在元素上一样,元素里不透明的地方,光线无法穿透形成投影

<span class="icon-del"></span>
.icon-del {
    background: url(../images/delete.png) no-repeat center;
    width: 20px;
    height: 20px;
    display: inline-block;
    -webkit-filter: drop-shadow(red 20px 0);
    filter: drop-shadow(red 20px 0);
}
alt

我们可以看到在原图标的右侧,出现红色的投影。现在需要做的是把原来图标隐藏起来

<span class="icon-wrapper">
    <span class="icon-del"></span>
</span>
.icon-wrapper {
    display: inline-block;
    width: 20px;
    height: 20px;
    overflow: hidden;
    position: relative;
}
.icon-del {
    background: url(../images/delete.png) no-repeat center;
    width: 100%;
    height: 100%;
    position: absolute;
    left: -20px;
    display: inline-block;
    border-right: 20px solid transparent;
    -webkit-filter: drop-shadow(red 20px 0);
    filter: drop-shadow(red 20px 0);
}
alt

注意:图标的增加了个和本身宽度一致的右侧透明边框,让阴影投射在边框上。如果没有右侧边框,则元素完全处于不可见状态,drop-shadow不能生效(设想下,看不见的东西,自然没有投影)

优点:不需要额外的图标
缺点:需要两层DOM结构

background-blend-mode: 背景混合模式

简单来说,元素可以设置多个背景,这些背景按某种模式混合

<span class="icon-gear"></span>
.icon-gear {
    background-image: url(../images/gear.png);
    background-color: red;
    background-size: cover;
    width: 64px;
    height: 64px;
    display: inline-block;
    background-blend-mode: lighten;
}

图标(注意要求是黑色的图标)设置图片背景和颜色背景,然后按照lighten模式混合

lighten模式可以简单理解为:当背景叠加时,显示亮色。本例子中,黑色的图标和其他颜色的背景色叠加,自然显示背景色

alt

优点:写法简洁
缺点:兼容性不好


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK