Add Custom Fonts in Magento 2: Guide To Using Custom Fonts

Add Custom Fonts in Magento 2: Guide To Using Custom Fonts

Are you looking to enhance your Magento store with custom fonts? Implementing a Magento custom font allows you to integrate personalized font styles, giving your site a distinct and professional appearance.

This tutorial will cover how to add custom fonts in Magento 2.

Best Magento Hosting now

Key Takeaways

  • Learn to add custom fonts, use Google Fonts, and customize your Magento theme.

  • Get an overview of how family-name and font family define your custom fonts in CSS declarations.

  • Understand how font properties help control font weight, style, and loading behavior.

  • Get insights into the fonts that are used in your Magento theme.

  • Discover ways to download font files in various formats for cross-browser support.

9 Steps To Include Custom Fonts In Magento 2

  1. To add font files to your local theme directory, place them in: app/design/frontend/<your_vendor_name>/<your_theme_name>/web/fonts

  2. To add external fonts, reference them in the page configuration file.

  3. If you are building a theme using the UI library, declare the custom font by adding the .lib-font-face mixin to the following file: app/design/frontend/<your_vendor_name>/<your_theme_name>/web/css/source/_typography.less

.lib-font-face(
    @family-name:'<custom_font_name>',
    @font-path: '@{baseDir}fonts/<path_to_font_file>',
    @font-weight: <font_weight>,
    @font-style: <font_style>,
    @font-display: <auto|block|fallback|optional|swap>
);

Note:

  • @{baseDir} refers to the app/design/frontend/<your_vendor_name>/<your_theme_name>/web directory.

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

  1. The mixin generates the CSS that includes the font. Here’s an example 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#OpenSans') format('svg');
  font-weight: 300;
  font-style: normal;
  font-display: swap;
}
  1. If specifying a format, enclose it in single quotes, e.g., @font-format: 'ttf' with @font-type: 'truetype'. Available types are woff, woff2, ttf, eot, otf, and svg.
.lib-font-face(
   @family-name:'<custom_font_name>',
   @font-path: '@{baseDir}fonts/<path_to_font_file>',
   @font-format: '<ttf|woff|woff2|eot|otf|svg>',
   @font-weight: <font_weight>,
   @font-style: <font_style>,
   @font-display: <auto|block|fallback|optional|swap>,
   @font-type: <font_type>
);
  1. In the Blank theme, @font-display: swap is declared by default in:

app/design/frontend/Magento/blank/web/css/source/_typography.less

Default fallback web fonts are located in the following:

lib/web/css/source/lib/variables/_typography.less

To include custom fonts for icons in the Blank theme, locate the icon font files in:

lib/web/fonts/Blank-Theme-Icons

  1. The _typography.less file defines the icon font path and name. The _icons.less file uses these files to define the icon font face.

  2. Call the .lib-icon-font mixin to apply icon fonts throughout the theme:

.icon-calendar {
    .lib-icon-font(
        @icon-calendar,
        @_icon-font-size: 28px
    );
}
  1. For customizing imported fonts, consider using IcoMoon. To override Luma or Blank theme icon fonts, change the font-path in the _theme.less file:
// Fonts
@icons__font-path: '@{baseDir}fonts/Theme-Icons';         
// Add your fonts in your-theme/web/fonts
@icons__font-name: 'Theme-Icons';

Note: With uploaded icons from IcoMoon, if a "404 error woff2 file icon not found" occurs, copy the woff file to woff2. If your theme doesn't use the UI library, include the font in your theme's CSS files using the @font-face CSS rule.

Font File Types

Font File Type Description
WOFF (Web Open Font Format) - Designed for use on the web
- Compresses fonts to reduce file size, improving load times
- Supported by all modern browsers
WOFF2 - An improved version of WOFF with better compression
- Smaller file size leads to faster loading
- Supported by all modern browsers
TTF (TrueType Font) - Developed by Apple and Microsoft
- Widely supported on both web and desktop applications
- Larger file size compared to WOFF formats
EOT (Embedded OpenType) - Created by Microsoft
- Primarily used for Internet Explorer compatibility
- Compressed format but less commonly used today
OTF (OpenType Font) - Developed by Adobe and Microsoft
- Supports advanced typographic features
- Suitable for both web and print
SVG (Scalable Vector Graphics) - Vector-based format that can be scaled to any size
- Can include multiple colors and gradients
- Mainly used for icons and complex graphics, less common for standard text fonts

Why Include A Set Of Built-In Fonts In Magento 2?

Reasons to include built-in custom fonts in Magento 2

1. Create a unique brand identity

Custom fonts help set your store apart visually and make it more memorable. Using the same fonts consistently across your site and marketing builds a stronger brand.

2. Improve readability

Well-chosen fonts optimized for the web can make your content easier and more pleasant to read. This enhances user experience and keeps visitors on your site longer.

3. Convey the right tone and personality

Fonts have their own personality. They can help convey the attitude and style of your brand, from casual and friendly to serious and professional.

4. Stand out from competitors

If competing stores use default fonts, a custom font helps differentiate your brand. It shows you have put extra effort into your store's design.

Tips For Adding Fonts In Magento

Tip Benefit
Use web-optimized font formats like WOFF Provides the best performance and faster loading.
Subset your font files only to include the characters you need Reduces font file sizes for faster downloading.
Declare fallback system fonts in case custom fonts fail to load Ensures text is still readable if custom fonts don't load.
Minimize the number of custom fonts Avoids slowing down page loads with too many fonts.
Preload key fonts used above-the-fold Speeds up text rendering for important content.
Use the size-adjust CSS property Maintains consistent font sizes when swapping fonts.

How To Use Custom Fonts With Hyvä?

1. Tailwind configuration

Combine the font in your CSS files with the font-family property, such as:

font-family: 'Roboto', sans-serif;

To use it with Tailwind CSS, add the font to your tailwind.config.js file. Refer to the Tailwind documentation for various ways to declare the font. For example, to use it as the default font-sans:

theme: {
  extend: {
    fontFamily: {
      sans: ['Roboto', ...defaultTheme.fontFamily.sans],
    },
  },
}

For this to work, you need to import the defaultTheme object. Add the following to the top of your tailwind.config.js file:

const defaultTheme = require('tailwindcss/defaultTheme');

2. Google fonts

When selecting a Google font on fonts.google.com, a default implementation is provided:

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">

You can include a modified version in your Magento_Theme/layout/default_head_blocks.xml file.

Note: The URL uses HTML & notation.

<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" type="text/css" src_type="url"/>

To add the preconnect resources, add a custom block to the head. For example:

<referenceBlock name="head.additional">
    <block class="Magento\Framework\View\Element\Text" name="custom.fonts">
        <arguments>
            <argument name="text" xsi:type="string">
                <![CDATA[
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
                ]]>
            </argument>
        </arguments>
    </block>
</referenceBlock>

Note: Be cautious when using Google fonts directly from Google servers, as it may not be GDPR compliant. Many websites have been fined for automatically requesting Google fonts.

To use the Google font files locally, use a helper to select the desired formats. Download the files and include them in your project.

3. Local font files

To register the fonts and reference their locations, use @font-face CSS rules. For example:

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url(../fonts/roboto.woff2) format('woff2');
}

Each different font in the family (varying in font-weight and font-style) needs its own declaration. These declarations do not load the font automatically. The font is only loaded when used in CSS as a font-family property, like font-family: "Roboto";, or with the appropriate Tailwind class.

There were different formats for font files in the past (e.g., .ttf, .otf, .eot). However, it is now recommended to use only woff2 or woff files.

Note: You can use custom font files or downloaded Google font files to include them locally from your web server.

To include the fonts:

  • Add the font files to a fonts/ folder in your theme’s web/ directory.

  • Add the @font-face styles to a CSS file, for example, in web/tailwind/components/typography.css.

  • Ensure the paths to the font files are correct. The generated CSS file will be in web/css, so ../fonts/ will refer to web/fonts/.

4. Preloading/preconnect

It is often recommended to preload fonts used above the fold. This helps avoid layout shifts and ensures fast delivery. It can also impact the LCP since preloading fonts blocks the first render.

To prevent layout shifts, set the correct system fallback fonts and line-heights to reserve space. You can also use size-adjust and ascent-override on the fallback font. This can be dynamically calculated for some fonts, like Google fonts.

Note: If you decide to preload fonts despite the warning, add the following snippet to your Magento_Theme/layout/default_head_blocks.xml file in the <head> section:

<font src="fonts/roboto.woff2"/>

This preloads the specified URL. When using files with multiple font formats, it is better to use preconnect. For this, add a custom block:

<referenceBlock name="head.additional">
    <block class="Magento\Framework\View\Element\Template" 
           name="custom.fonts"
           template="Magento_Theme::head.phtml" />
</referenceBlock>

In head.phtml, you can use something like:

<link rel="preconnect" href="<?= $block->getViewFileUrl('fonts/roboto.woff2') ?>">

Note: There are different opinions on whether to use preloading or not. Test your environment to ensure it produces the desired outcome.

5. Font-display options

In most cases, using the swap value for the font-display property is the best choice. This ensures text is displayed quickly while the web font loads in the background. This minimizes layout shifting. If the optional value is used, the web font will only be displayed if it arrives on time.

6. PostCSS plugin

You can use the PostCSS plugin postcss-font-magician. Specify the location of your font files in the PostCSS configuration. Automatically add the necessary styles to styles.css. For example:

require('postcss-font-magician')({
   hosted: ['../fonts/', '../fonts']
});

Troubleshooting Solutions For Declaring The Font In Your Theme In Magento

Potential Issue Troubleshooting Solution
Custom fonts not loading on frontend - Ensure font files are uploaded to the correct directory in your theme (e.g. web/fonts/)
- Check that font file paths are correct in .lib-font-face mixin
- Clear Magento cache and static content cache
Layout shifts or flash of unstyled text when fonts load - Use font-display: swap to show fallback font while custom font loads
- Preload key font files used above-the-fold in <head>
- Use fallback fonts that closely match the custom font's metrics
Custom fonts not applied to some text/elements - Check that the font-family is specified correctly in theme styles
- Ensure font-weight and font-style match the font file being loaded
- Verify the selectors are targeting the right elements
Custom fonts not working after the Magento upgrade - Re-add the font files and font-face declarations to your theme
- Check for changes in directory structure or less/CSS files
- Verify custom fonts weren't overwritten by new default fonts

FAQs

1. Can I use custom fonts in a child theme?

Yes, you can easily include custom fonts in a child theme. Add your font files to the child theme's web/fonts directory. Update the CSS in the child theme to reference these new fonts.

2. What do the values "300; font-style: normal; font-display: swap;" mean in a font declaration?

These values define the font's properties. 300 is the font-weight (light). font-style: normal means the font is not italic. font-display: swap tells browsers to use a fallback font until the custom font loads.

3. How can I disable Google Fonts in my default Magento theme?

To disable Google Fonts, you'll need to override the _theme.less file in your custom theme. Remove or comment out any @import statements referencing Google Fonts.

4. What's the difference between font_weight and font_style in Magento's font declarations?

font_weight determines the thickness of characters (e.g., normal, bold). However, font_style sets whether the font is italic or not.

5. Does Magento already include Montserrat font, or do I need to add it?

Magento 2 doesn't include Montserrat by default. You will need to add it either by linking to Google Fonts. Also, you can download and include the font files in your theme.

6. How can I add custom fonts to my theme files using XML in Magento 2?

Use the default_head_blocks.xml file in your theme. Add a line like this: <css src="css/custom-fonts.css" />. This will include your custom CSS file with font declarations.

CTA

Summary

With Magento custom font, you can easily add and customize fonts in Magento 2. It helps store owners to:

  • Ensure their store stands out and is compatible with their custom additions.

  • Establish a unique brand identity and distinguish their store from competitors.

  • Enhance user experience and improve text readability.

  • Provide a cohesive and polished appearance.

  • Better search engine rankings and improved loading times.

Consider Magento optimised server to implement custom fonts and font styles.

Dikshya Shaw
Dikshya Shaw
Technical Writer

Dikshya leverages her content marketing and writing proficiency to deliver fresh, insightful content. Her meticulous research ensures industry expertise and emerging trends within the Magento landscape.


Get the fastest Magento Hosting! Get Started