How to include custom fonts in Magento 2

0
277
magento-fonts

Magento already provides a set of default fonts but you can manage yourself to include some custom fonts as well. In this post, we will guide you how to add locally stored custom fonts into your Magento theme.

In order to keep your customization stable and ensure that new upgrades will not overwrite your customization, the default Magento theme files should not be modified. Your theme’s stylesheet must be the place for custom fonts.

How to include custom fonts in Magento 2

1. Insert font files to your local theme directory:

app/design/frontend/<your_vendor_name>/<your_theme_name>/web/fonts.

2. In case you might build a theme by the Magento UI library, declare the font by adding the mixin .lib-font-face to the file app/design/frontend/<your_vendor_name>/<your_theme_name>/web/css/source/_typography.less

.lib-font-face(
@family-name:'<any_font_name>’,
@font-path: ‘@{baseDir}fonts/<path_to_font_file>’,
@font-weight: <font_weight>,
@font-style: <font_style>
);

  • @{baseDir} stands for the app/design/frontend/<you_vendor_name>/<your_theme_name>/web directory.
  • <path_to_font_file> includes the font file name, but without the extension. For example, @font-path: '@{baseDir}fonts/Luma-Icons' for the font stored in web/fonts/Luma-Icons.woff.

The mixin generates the CSS, which includes the font. The following example shows how to generate CSS for the Open Sans font in the Blank theme:

 @font-face {
     font-family: 'Open Sans';
     src: url('../fonts/opensans/light/opensans-300.eot');
     src: url('../fonts/opensans/light/opensans-300.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans/light/opensans-300.woff2') format('woff2'), url('../fonts/opensans/light/opensans-300.woff') format('woff'), url('../fonts/opensans/light/opensans-300.ttf') format('truetype'), url('../fonts/opensans/light/opensans-300.svg#Open Sans') format('svg');
     font-weight: 300;
     font-style: normal
     font-display: swap;
 }

 

@font-display: swap is declared by default for Magento Blank theme in app/design/frontend/Magento/blank/web/css/source/_typography.less.

Fallback web fonts that are used by default in Magento are located in lib/web/css/source/lib/variables/_typography.less.

That’s it. Hope you’ll find it helpful.