将自定义字体添加到Rails 4的官方方法?
我正在研究如何将自定义字体添加到我的Rails应用程序中,例如通过在assets文件夹中添加一个fonts
文件夹 – 我无法找到一个“官方”Rails方式来解决这个问题。
是的,这里有很多关于此事的问题/答案,所有这些似乎与他们自己的黑客有关。 但是,在Rails着名的“配置约定”下,不应该采用这种常见做法吗?
或者如果我错过了 – 关于如何在Rails应用程序中组织字体的文档参考?
是的,给出的链接将很好地解释,但是如果你需要另一个详细的解释,那么这里是
-
首先在您的应用程序中使用自定义字体,您需要下载字体文件,您可以尝试http://www.1001freefonts.com/
http://www.piccsy.com/everything-design/并寻找字体
几乎没有最流行的字体文件格式主要是.otf(开放格式).ttf(真实格式).woff(Web开放字体格式)
-
您可以将下载的字体移动到app / assets / fonts /下的app文件夹中
-
下载文件后,您需要“声明”您将在css中使用的字体,如下所示
@font-face { font-family: "Kaushan Script Regular"; src: url(/assets/KaushanScript-Regular.otf) format("truetype"); }
-
最后,您可以使用您刚刚在任何地方声明的font-family
#e-registration { font-family: "Kaushan Script Regular"; }
希望这可以帮助。
刚刚做到了……
-
在assets / fonts /目录中下载并保存字体文件(eot,woff,woff2 …)
- 在你的config / application.rb中添加这行config.assets.paths << Rails.root.join(“app”,“assets”,“fonts”)
它的作用是预编译你的fonts文件夹,就像你默认使用你的图像,样式表等一样。
-
并确保此行设置为true config.assets.enabled = true
-
在你的sass / scss中,甚至用
标签内联
@font-face { font-family: 'Bariol Regular'; src: font-url('Bariol_Regular_Webfont/bariol_regular-webfont.eot'); src: font-url('Bariol_Regular_Webfont/bariol_regular-webfont.eot?iefix') format('eot'), font-url('Bariol_Regular_Webfont/bariol_regular-webfont.woff') format('woff'), font-url('Bariol_Regular_Webfont/bariol_regular-webfont.ttf') format('truetype'), font-url('Bariol_Regular_Webfont/bariol_regular-webfont.svg#webfont3AwWkQXK') format('svg'); font-weight: normal; font-style: normal; }
请注意,您应该使用font-url
helper而不是css'url来解决Rails在预编译资产时完成的指纹识别
最后,在CSS文件中设置font-family
body { font-family: 'Bariol Regular', serif; }
免费提示:这就是说,性能方面的最佳方法是使用JS进行设置,以便这些字体异步加载。 检查这个加载器: https : //github.com/typekit/webfontloader
我在上面列出的方法上遇到了一些麻烦,因为生产css没有指向编译的ttf字体,所以我成功地使用了从https://gist.github.com/anotheruiguy/7379570借来的替代方法:
-
将所有字体文件放在
assets/stylesheets/fonts
。 例如assets/stylesheets/fonts/digital_7.ttf
。 -
我在我们使用的.scss文件中定义:
@font-face { font-family: 'Digital-7'; src: asset-url('fonts/digital_7.ttf') format('truetype'); font-weight: normal; font-style: normal; }
-
我在其他.scss文件中使用了自定义字体:
.digital-font { font-family: 'Digital-7', sans-serif; font-size: 40px; }
这样说,更简洁的方法是将字体定义(在此示例中为digital_7_mono.ttf)放在单独的站点上。
如果您正在使用Cloudfront,例如,在名为my_path
的Cloudfront目录中,上传您的字体文件,然后定义一个css文件(例如digital_fonts.css
)
@font-face { font-family: 'Digital-7-Mono'; font-weight: normal; font-style: normal; src: local('Digital 7 Mono'), local('Digital-7-Mono'), url('https://mycloudfront_site.com/my_path/digital_7_mono.ttf') format('truetype'); }
在你的html中,在标记内,添加: