Skip to content

图标颜色

本教程是 Iconify for Svelte 教程 的一部分。

您只能更改单色图标的颜色。某些图标(例如表情符号)具有无法更改的硬编码配色方案。

要更改单色图标的颜色,只需更改文本颜色,或使用 color 属性,或添加带有颜色的 style

All icons inside this div are light blue, including a bell icon and attachment icon
This text and icon are orange:
Red home icons (shows different ways to change color):
Icon with palette:
svelte<script>
   import IconifyIcon from '@iconify/svelte';
</script>

<style>

   /*
       Cannot target component in CSS, target SVG
       instead using Svelte's :global() function

       This is equivalent of adding inline={true} to each icon
   */

   div :global(svg) {
       vertical-align: -0.125em;
   }

   /* Change text color for ".orange-block" to #e70 */
   .orange-block {
       color: #e70;
   }
   /* Change all icons inside ".light-blue-block" to #08f */
   /*
       Must use :global() because Svelte cannot assign style to
       a component, so need to target SVG generated by component.
   */

   .light-blue-block :global(svg) {
       color: #08f;
   }

   /* Change text color for ".red-icon" to #e00 */
   /*
       Must use :global() because Svelte cannot assign style to a
       component by class name, it can only work with standard HTML tags.
   */

   div :global(.red-icon) {
       color: #e00;
   }
</style>

<div>
   <div class="light-blue-block">
       All icons inside this div are light blue, including a bell icon
       <IconifyIcon icon="bi:bell-fill" />
       and stopwatch icon
       <IconifyIcon icon="bi:stopwatch" />
   </div>
   <div class="orange-block">
       This text and icon are orange:
       <IconifyIcon icon="bi:bell-fill" />
   </div>
   <div>
       Red home icons (shows different ways to change color):
       <IconifyIcon class="red-icon" icon="bx:bx-home" />
       <IconifyIcon style="color: red" icon="bx:bx-home" />
       <IconifyIcon color="red" icon="bx:bx-home" />
   </div>
   <div>
       Icon with palette:
       <IconifyIcon icon="noto:paintbrush" />
   </div>
</div>

颜色仅适用于没有调色板的图标。带有调色板的图标(如上方示例中的画笔图标)的颜色无法更改。

更改颜色的方法与更改文本颜色的方法相同。

RGBA 和 HSLA 颜色

避免使用 rgbahsla 颜色。某些图标包含多个相互叠加的图层。使用半透明颜色会导致各图层均可见。

相反,请使用纯色,并通过 opacity 添加透明度。这样浏览器会先以纯色渲染形状,然后再对整个图标应用透明度。

fill 和 stroke

避免在样式表中使用 fillstroke,除非你是为特定图标使用它们。

并非所有图标都相同。有些图标使用 fill 来定义形状,有些则使用 stroke。如果设置了 fill,可能会导致本不应填充的形状被填充。