Magento 2 store owners may want to get creative with fonts once in a while!
Instead of paying for the fonts library, one can add & use Google fonts in Magento 2 store.
For example, your business targets kids, or women, or professionals, you may want to choose the font of your website accordingly for each case.
Google fonts are readily available and easy to use. Also, they are free of cost and the store owner can choose among thousands of fonts available that will be suitable for their customer base or type of business. Also Google Fonts GDPR compliance involves using Google Fonts in a way that adheres to the General Data Protection Regulation (GDPR) guidelines.
Also, if you are a Magento developer and need fonts other than the default ones to use in your Magento extensions or themes, you may use the below solution.
Method to Add & Use Google Fonts in Magento 2
Put the following code at Vendor\Extension\View\frontend\layout\default_head_blocks.xml file or Vendor\Your_Theme\Magento_Theme\layout\default_head_blocks.xml
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <link rel="stylesheet" type="text/css" src="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;0,800;1,300;1,400;1,600;1,700;1,800" src_type="url" /> </head> </page>
You can import multiple google fonts by using:
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <link rel="stylesheet" type="text/css" src="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;0,800;1,300;1,400;1,600;1,700;1,800&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&" src_type="url" /> </head> </page>
or you can use directly .phtml file as shown below:
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;0,800;1,300;1,400;1,600;1,700;1,800" rel="stylesheet" />
Import multiple google fonts in phtml file
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;0,800;1,300;1,400;1,600;1,700;1,800&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&" rel="stylesheet" />
Once done, you can use the Google fonts like this:
font-family: 'Roboto'
That’s it. Let your creative juices flow freely while developing your Magento site, extensions, or themes when it comes to fonts!
Please share the post with the Magento Community via social media.
Thank you!