【问题标题】:Is it possible to use Icons with css:before without hardcoding the code?是否可以在不硬编码代码的情况下使用带有 css:before 的图标?
【发布时间】:2017-01-05 05:43:51
【问题描述】:

我正在使用回答here on StackOverflow 的方法将自定义警察定义与其他类一起使用。该方法总结如下:

[class^="icon-"]:before,
[class*=" icon-"]:before {
    font-family: FontAwesome;
}
.icon-custom:before {
    content: "\f0c4";
}

当我使用自定义类来使用它时,我必须使用库生成的代码:

i:after { 
    content: '\f0c4';
}

如果这个代码f0c4在库中发生变化,我想避免一一报告每个自定义类的变化。我决定使用 Sass 或 Less 来解决这个问题。 如下所示,但它不起作用。

i:after {
   .icon-custom
}

使用 Sass 或 Less,是否有可能避免这个神奇的数字?

我知道这是可能的:

i:after {
   content: @custom-code-value
}

但我更愿意避免更改 @custom-code-value: : "\f0c4"; 它是唯一的解决方案吗?

【问题讨论】:

  • 为什么投反对票?不清楚吗?

标签: css sass less


【解决方案1】:

您可以尝试将所有内容值分组到一个地图变量

我为你改编了一个例子

SCSS

// Map variable
$icons: (
  facebook   : "\f0c4",
  twitter    : "\f0c5",
  googleplus : "\f0c6",
  youtube    : "\f0c7"
);

// Mixin doing the magic
@mixin icons-list($map) {
  @each $icon-name, $icon in $map {
    @if not map-has-key($map, $icon-name) {
      @warn "'#{$icon-name}' is not a valid icon name";
    }

    @else {
      &--#{$icon-name}::before {
        content: $icon;
      }
    } 
  }
}

// How to use it
.social-link {
    background-color: grey;
    @include icons-list($icons);
}

CSS

// CSS Output
.social-link {
  background-color: grey;
}
.social-link--facebook::before {
  content: "";
}
.social-link--twitter::before {
  content: "";
}
.social-link--googleplus::before {
  content: "";
}
.social-link--youtube::before {
  content: "";
}

因此,您只需维护该 $icons 变量,以防某些值发生变化。希望你能明白。

【讨论】:

  • 不清楚。为什么所有图标的值都是“”; ?所以应该是像 "\f0c4" 这样的值
猜你喜欢
  • 1970-01-01
  • 2019-02-12
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多