Explain Codes LogoExplain Codes Logo

How can I change the Bootstrap default font family using font from Google?

html
responsive-design
css-variables
sass
Nikita BarsukovbyNikita Barsukov·Oct 23, 2024
TLDR

Swiftly switch to a Google Font from Bootstrap's default by plugging the font's link into your HTML and overriding Bootstrap's font in CSS:

<link href="https://fonts.googleapis.com/css?family=Oswald:400,700&display=swap" rel="stylesheet">
body { font-family: 'Oswald', sans-serif !important; // "Oswald" just elbowed out Bootstrap's default ;) }

Update 'Oswald' with your choice of Google Font. Be sure to flex the power of !important to bully Bootstrap rules into submission.

Moreover, if you plan to use various font weights, specify them in the URL parameters of the <link> or @import statement.

Deep dive

Refined look with Sass

Sass is a tool that brings some order to the sometimes chaotic world of CSS. It allows overwriting Bootstrap's variables in a neat way:

$body-font-family: 'Oswald', sans-serif; // "Oswald" swoops in like a superhero dressing for work @import "bootstrap"; // The rest follow obediently

For seamless Sass customization, reference _variables.scss. Use a compiler like gulp-sass to sew together a well-tailored, optimized stylesheet.

CSS Closet Organization

Organization, my friend, is key. Maintain your styling in a separate custom.css or custom.scss file:

1. `_variables.scss`: Affects change from within - redefines Bootstrap’s variables 2. `custom.scss`: Prepares the red carpet for Oswald 3. `_custom_compiled.css`: The outcome of Sass compilation, steps in after Bootstrap's CSS

Link the _custom_compiled.css in your HTML header, right after the Bootstrap CSS.

Twisting knobs with CSS Variables in Bootstrap 5

Bootstrap 5 brought a new toy - CSS variables for easier theming. Here's how you set Oswald as the fashion statement:

:root { --bs-body-font-family: 'Oswald', sans-serif; // Oswald - elevated to a CSS variable, talk about moving up in life! }

Bootstrap's official documentation is your guide to mastering CSS variables.

Import medicine and optimization tips

When it comes to pulling Google Fonts off the rack, the <link> tag beats @import at the performance game - owing to parallel loading:

<link href="https://fonts.googleapis.com/css?family=Oswald:400,700&display=swap" rel="stylesheet">

However, @import carries the day in case your CSS or Sass files deeply desire a single roof:

@import url('https://fonts.googleapis.com/css?family=Oswald:400,700&display=swap'); // Oswald, reporting for duty!

Swift font delivery

Whilst defining font families and weights, employ font-display strategies, and only call for necessary font weights. You don't want an overweight font slowing down your site now, would you?

<link href="https://fonts.googleapis.com/css?family=Oswald:400,700&display=swap&font-display=swap" rel="stylesheet"> // Trim and fit, Oswald ready to sprint!