Is it possible to use Icons with css:before withou

2019-07-18 10:25发布

I am using the method answered here on StackOverflow to use custom police definition with other classes. This method is summarized below:

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

When I'm using a custom class to use it, I have to use the code generated by the library:

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

In case this code f0c4 change in the library, I would like to avoid reporting the change in every custom class one by one. I decided to use Sass or Less to be able to deal with this problem. It would be like below but it does not work.

i:after {
   .icon-custom
}

With Sass or Less, is it possible to avoid this magic number?

I know this will be possible:

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

But I prefer to avoid changing the @custom-code-value: : "\f0c4"; Is it the only solution?

标签: css sass less
1条回答
Summer. ? 凉城
2楼-- · 2019-07-18 11:01

You can try to group all the content value in a map variable

I adapted for you an example

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: "";
}

So you only have to maintain that $icons variable in case some values change. hope you get the idea.

查看更多
登录 后发表回答