Explain Codes LogoExplain Codes Logo

How can I use Google's Roboto font on a website?

html
font
performance
sass
Nikita BarsukovbyNikita Barsukov·Aug 19, 2024
TLDR

Use the following <link> to embed Google's Roboto font:

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">

Apply it in CSS this way:

body { font-family: 'Roboto', sans-serif; }

Now, Roboto is up and running! Use wght@400;700 to access normal and bold weights. Ready, set, code!

Choosing and using Roboto variations

Adding the Roboto flavor

Roboto comes with a variety of weights and styles. Pick your choice:

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400;700;900&display=swap" rel="stylesheet">

This includes thin, regular, bold, and black weights. Because let's be honest, who doesn't enjoy a little variety?

Making Roboto yours

Host Roboto locally to have more control and potentially enhance loading performance. Here is the trick:

@font-face { font-family: 'Roboto'; font-style: normal; font-weight: 400; src: local('Roboto'), local('Roboto-Regular'), url(/fonts/Roboto.woff2) format('woff2'); } body { font-family: 'Roboto', sans-serif; }

It's like having Roboto in your own wardrobe. Just bring it out with local(), and specify the src path to your font files. Please remember to invite all the weights and styles to the party!

Digging deeper with Roboto

Using the @font-face magic

Multitasking, anyone? Hand-pick your weights and ensure the right directory structure. Yes, organization matters:

@font-face { font-family: 'Roboto'; font-weight: 400; src: url('/fonts/roboto-regular.woff2') format('woff2'); } @font-face { font-family: 'Roboto'; font-weight: 700; src: url('/fonts/roboto-bold.woff2') format('woff2'); }

Here, each @font-face points to different font files and specifies the accurate font-weight. Remember, accuracy is key.

Troubleshooting your Roboto

Issues might pop up everywhere, making it worse they may:

  • Cross-browser compatibility: Use .woff2 format for the superheroes (aka modern browsers) and provide plans B, C and D (aka fallbacks).
  • Loading performance: Preload fonts to prevent the notorious "Flash of Unstyled Text" (FOUT). Because nobody likes a slow show!
  • Rendering issues: Don't skip on quality control. Test across gadgets and ensure font file integrity. Because pixel-perfection is not overrated.

Getting sassy with SASS

Want to make Roboto your constant companion? Use variables in SASS:

$roboto: 'Roboto', sans-serif; body { font-family: $roboto; } h1 { font-family: $roboto; font-weight: 700; }

Bail on repetitive styles and make your coding life easier. Your future self will thank you!