goto goto - 3 months ago 8
Sass (Sass) Question

Is it possible to use Icons with css:before without hardcoding the code?

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?

Answer

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.

Comments