Magento 2 : How to include new Custom Font

Let’s suppose you already have TTF file of your favourite Font Family. In my case it is Futura-Book. To start with we need to generate the web package of our font. I have used the famous https://transfonter.org/ to generate it. They accept all format like TTF, OTF, WOFF, WOFF2 or SVG, 10 MB per file.

Complete Font Package with all the formats, styelsheet and demo.html
demo.html

To ensure the stability of your customizations and prevent upgrades from overwriting your customizations, do not change the default Magento theme files. You must include custom fonts in the your theme’s stylesheet.

Magento DevDocs

Step 1 : Add all the font files to your theme folder.

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

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

    .lib-font-face(
        @family-name: 'Futura-Book',
        @font-path: '@{baseDir}fonts/Futura-Book',
        @font-weight: normal,
        @font-style: normal
    );

Where:

  • {@baseDir} stands for the app/design/frontend/<you_vendor_name>/<your_theme_name>/web directory. Default value in Magento Blank theme is : @baseDir: ‘../’;

The mixin generates the CSS for our Futura-Book font.

 @font-face {
     font-family: 'Futura-Book';
     src: url('../fonts/Futura-Book.eot');
     src: url('../fonts/Futura-Book.eot?#iefix') format('embedded-opentype'),
url('../fonts/Futura-Book.woff2') format('woff2'), url('../fonts/Futura-Book.woff') format('woff'), 
url('../fonts/Futura-Book.ttf') format('truetype'), 
url('../fonts/Futura-Book.svg#Futura-Book') format('svg');
     font-weight: normal;
     font-style: normal;
 }

Step 3 : Simply run the following commands to deploy static content and flush cache.

php bin/magento setup:static-content:deploy --theme Magento/backend --theme Vendor/MyTheme
php bin/magento cache:flush

Above commands will deploy your theme only.

Step 4 : Use font by just adding font-family: ‘Futura-Book’;

Leave a Reply

Your email address will not be published. Required fields are marked *