Using Google or Bunny Fonts in Laravel with Tailwind
Easily integrate Google or Bunny Fonts in Laravel (and use them with Tailwind).
First Things First
Using a custom font with Laravel isn't exactly straightforward for newcomers. The good news is, it's pretty easy to do!
I'm going to assume you have an existing Laravel installation, with Tailwind included. See the docs if you need a reference. First things first- we'll pick out a Google Font or Bunny Font to use. If you can't already tell, I'm partial to Ubuntu.
Adding a Font
Once you select a font, you'll need to select the weights you want to use. I like to use 300 through 800 (if available), so that I can make use of Tailwind's font-light
and font-extrabold
classes.
Once you've selected your font and weights, you'll copy the embed link and paste this within the <head>
tags of your project:
<head> {{-- ... --}} {{-- Bunny Fonts --}} <link rel="preconnect" href="https://fonts.bunny.net"> <link href="https://fonts.bunny.net/css?family=ubuntu:300,400,500,700" rel="stylesheet" /> {{-- Google Fonts --}} <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=Ubuntu:wght@300;400;500;700&display=swap" rel="stylesheet"></head>
Next, you'll add a key/value in tailwind.config.js
to reference the font. This key/value pair goes within the theme.fontFamily
object. The key represents what you'd like to name the class, the value will come from the font-family name.
module.exports = { theme: { fontFamily: { 'ubuntu': 'Ubuntu' }, }}
You can find the font-family name on the respective Google/Bunny font page:
Using the Font
To reference the font with Tailwind you'll need to re-build your assets. In my case, I'd use npm run dev
(or watch, or prod). You should now be able to use the font as a Tailwind class using the key name you added in the previous step.
<body class="antialiased bg-stone-100 font-ubuntu">{{-- ... --}}</body>
That's all there is to it!
With the Tailwind CSS IntelliSense VS Code plugin, my editor immediately recognizes the new class we've added. Check out the Tailwind Docs to use it with your editor, I highly recommend it.