如何使用CSS改变图标颜色

3

我有一个消息状态类,允许用户使用不同的背景颜色CSS规则区分消息状态。 我只想改变消息中放置的图标的颜色,例如使用<i class="glyphicon glyphicon-ok">

CSS当前如下:

.message-status {
    padding:18px 24px;
    margin:0 0 24px;
    border-radius:4px;
    color:#fff;
    h2 { margin-top:0; }
    &.status1 { background:#35c671; }
    &.status2 { background:#565a5c; }
    &.status3 { background:#565a5c; }
    &.status4 { background:#565a5c; }
    &.status5 { background:#565a5c; }
}

我只想改变消息状态div中图标的颜色,而当前它只能改变背景颜色。

感谢您的时间。


你想要每个状态有不同的颜色吗?还是在.message-status中都一样? - dfsq
可能是Can I add color to bootstrap icons only using CSS?的重复问题。 - D-side
我猜测为 .message-status i {} 制作一个新的选择器,然后您就可以更改其中图像标签的背景。 - Paul Zepernick
是的,你可以。color 属性使图标继承它们所在文本的颜色。这很合理,因为它们只是来自图标字体的符号,就像文本一样。 - D-side
3个回答

1
假定每个图标的颜色应该由状态容器定义,您可以这样操作:
.message-status {
    padding:18px 24px;
    margin:0 0 24px;
    border-radius:4px;
    color:#fff;
    h2 { margin-top:0; }

    &.status1 { 
        background:#35c671; 
        .glyphicon { color: #001; }
    }
    &.status2 { 
        background:#565a5c; 
        .glyphicon { color: #002; }
    }
    // etc ...
}

0

我不确定这适合你:

.message-status {
    padding:18px 24px;
    margin:0 0 24px;
    border-radius:4px;
    color:#fff;
    h2 { margin-top:0; }
    &.status1 { background:#35c671; }
    &.status2 { background:#565a5c; }
    &.status3 { background:#565a5c; }
    &.status4 { background:#565a5c; }
    &.status5 { background:#565a5c; }
}

    .status1 .glyphicon { color:#35c671; }
    .status2 .glyphicon { color:#565a5c; }
    .status3 .glyphicon { color:#565a5c; }
    .status4 .glyphicon { color:#565a5c; }
    .status5 .glyphicon { color:#565a5c; }

0
如果您想更改此特定图标的颜色(而不是具有相同类 .message-status 的其他图标),只需将另一个类添加到与此相同的 div/span 中。可以通过JavaScript(jQuery选择器)或重新加载页面来实现。
<div class="message-status newcolor"> ...  <i class="glyphicon glyphicon-ok"> ... </div>

在你的CSS中添加:

.newcolor { color:#444 !important;}

如果颜色应该遵循.status1,status2等,则我们需要稍微修改一下。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接