Quantcast
Channel: Federico Ramírez
Viewing all articles
Browse latest Browse all 10

FontAwesome Sass mixin for Rails

$
0
0

This is gonna be a short one. I’ve always used and loved FontAwesome, it has a bunch of well designed icons you can use for free in your app. There are some alternatives of course, but FA is well supported pretty much anywhere.

For example, if you want to integrate FA with Rails, all you have to do is install the font-awesome-rails gem, @include "font-awesome"; and you are done! It even includes some nice helpers to make your life easier.

One thing it lacks though is Sass mixins. There are times where you want to set an icon using CSS, most likely in combination with :after and :before pseudo-selectors. For example, one might do something like this:

.my-element {
  // some styles...

  &:after { 
    font-family: FontAwesome;
    content: '\f004';
    display: inline-block;
  }
}

Why did I use \f004 as the content? Well that’s because I want a heart icon, and the unicode glyph for that icon is that ugly hex number. Nobody wants to check icons one by one in order to get the code, it’s slow and annoying. This is why you should use a mixin!

@mixin fa($icon) {
  @extend .fa;
  @extend .fa-#{$icon}:before;
}

Using that little mixin you can now rewrite the scss as follows:

.my-element {
  // some styles...

  &:after { 
    @include(heart);
    display: inline-block;
  }
}

You can even play around and generate more-specific mixins which automatically add an :after or :before element, that way we could write code which is shorter and more readable:

.my-element {
  // some styles
  @include fa-after(heart)
}

Pretty neat! Hope you find this little post useful, and please let me know what you think in the comments below. Cheers!


Viewing all articles
Browse latest Browse all 10

Trending Articles