LoginSignup
82
71

More than 5 years have passed since last update.

Font Awesome 5 Freeで疑似要素(:after,:before)のcontent指定する場合

Last updated at Posted at 2018-02-14

Font Awesome5のフリー版CDNを使った場合、疑似要素(:after,:before)のcontentにアイコンを指定する方法が、ver4とちょっとだけ違っていてハマったのでメモします。

CDNはこちらのCSS

<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">

CSSで font-family: "Font Awesome 5 Free";と指定

a::after {
  font-family: "Font Awesome 5 Free";
  content: "\f107";

  -webkit-font-smoothing: antialiased;
  display: inline-block;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
  line-height: 1;
}

ちなみにPro版だと font-weight: 900 (Solid), 400 (Regular or Brands), 300 (Light) と切り替えられるみたいです。

参考: https://fontawesome.com/how-to-use/web-fonts-with-css#pseudo-elements

追記) 2018.03.07
一部のアイコンには、 font-weight: bold; を指定しないと表示されない模様。現在調査中です。

//追記ここまで

またBrands(ブランド系)アイコンを使う場合はfont-familyの指定が違う模様。

.twitter::before {
  font-family: "Font Awesome 5 Brands";
  content: "\f099";
}

BrandsアイコンはFreeに全て同梱されててProとの差はないようなので(2018年2月14日時点)、Pro版購入しても修正の必要はなさそうです

SVG置換する場合

JS版だと 疑似要素内のfont-familyを検索して、SVGに置換してくれる。

CDNからJavaScriptを読み込む

<script>
  FontAwesomeConfig = { searchPseudoElements: true };
</script>
<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>

CSSの疑似要素に font-family、contentをそれぞれ記述

  • display: none; が必須。
  • font-familyで Solid,Regular,Brandsを指定
.sample1::before {
  display: none;
  font-family: "Font Awesome 5 Solid";
  content: "\f007";
}
.sample2::before {
  display: none;
  font-family: "Font Awesome 5 Regular";
  content: "\f1ea";
}
.sample3::before {
  display: none;
  font-family: "Font Awesome 5 Brands";
  content: "\f099";
}

.sample1 は実際にこんなHTMLに変換されます。

<a class="sample1"><svg class="svg-inline--fa fa-user fa-w-16" data-fa-pseudo-element=":after" aria-hidden="true" data-prefix="fas" data-icon="user" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 0c88.366 0 160 71.634 160 160s-71.634 160-160 160S96 248.366 96 160 167.634 0 256 0zm183.283 333.821l-71.313-17.828c-74.923 53.89-165.738 41.864-223.94 0l-71.313 17.828C29.981 344.505 0 382.903 0 426.955V464c0 26.51 21.49 48 48 48h416c26.51 0 48-21.49 48-48v-37.045c0-44.052-29.981-82.45-72.717-93.134z"></path></svg><!-- <i class="fas" data-fa-pseudo-element=":after"></i> --></a>

font-familyの指定を "Solid" を "Regular" に変えてもフリー版にない太さだったら表示されないので注意。
自由に変更できるのがPro版。
Free版は使いたいアイコンが"Solid"か"Regular"かを毎回確認しないといけないから少し面倒かも。

参考: https://fontawesome.com/how-to-use/svg-with-js#pseudo-elements

82
71
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
82
71