如何在Font Awesome中使用数据属性?

问题描述:

我想将 rel 内容转换为Font Awesome CSS图标,因此我不必为简单的菜单写20行。

I want to convert a rel content into a Font Awesome CSS icon, so I won't have to write 20 lines for a simple menu.

也许某些代码会使它更容易理解。

Maybe some code would make it easier to understand.

我尝试这样做:

a:before {content: "\(" attr(rel) ")"; font-family: 'FontAwesome';}

基本上我正在尝试转换 rel 并将其转换为有效的CSS规则。

Basically I am trying to convert the value inside the rel and convert it to a working CSS rule.

所以链接看起来像这样:

<a href="http://www.example.com" rel="f291">Example</a>

最终结果应类似于:

a:before {content: "\f291")"; font-family: 'FontAwesome';}


尽管该问题可能会重复到这篇文章。总而言之,您需要在其中使用HTML实体或Unicode字符本身以便在CSS content 属性中使用它。

Although the question may duplicate to this post. In a simple word - you'll need to use HTML entity, or the unicode character itself, in order to use it in CSS content property.

但是,将这项技术与Font Awesome一起使用是一个非常有趣的想法,所以我正在写这个答案,并为其添加更多信息。

However it's a very interesting idea to use the technique with Font Awesome, so I'm writing this answer, and adding the extra info for it.

我建议使用数据属性 data- 而不是 rel ,因为 rel 是为链接类型设计的。

I'd suggest to use data attributes data- instead of rel, as rel is designed for link types.

并且在此页面上有一套完整的Font Awesome Unicode表。您可以复制/粘贴Unicode字符或图标本身。下面的示例:

And on this page has a complete set of Font Awesome unicode tables. You can either copy/paste the unicode character, or the icon itself. Examples below:

@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css");

a::before {
  font-family: 'FontAwesome';
  content: attr(data-fa-icon);
}

<p><a href="#" data-fa-icon="&#xf206;"> Unicode example</a></p>
<p><a href="#" data-fa-icon=""> Icon example</a></p>