如何更改Bootstrap字体族?实操步骤及失效问题求助
Hey there! I totally get why the existing Stack Overflow answer felt confusing—let's walk through this in super simple terms so you can get your Google Font working with Bootstrap smoothly.
Step 1: Keep Your Google Fonts Import (Double-Check the Setup)
First, confirm you’ve got your chosen Google Font’s link in the <head> of your HTML file. It should look something like this (replace YourChosenFont with the font you picked):
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=YourChosenFont:wght@400;700&display=swap">
You don’t need to tweak this link—this just loads your desired font into the page so the browser can access it.
Step 2: Modify Bootstrap’s SCSS Variable (The Key Fix)
The issue with your earlier body selector approach is that Bootstrap applies font styles directly to most components (buttons, navbars, cards, etc.) using its own SCSS variables. These component styles have higher specificity than a plain body rule, so your override got ignored.
Here’s the correct way to do it:
- Open your main custom SCSS file (like
styles.scssorcustom.scss). - At the very top of this file, redefine Bootstrap’s font variable. Swap
"YourChosenFont"with your actual font name:$font-family-sans-serif: "YourChosenFont", -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !default;- You don’t need to delete the original system fonts! Putting your custom font first tells the browser to try loading it first, and fall back to the system fonts if it can’t find yours.
- The
!defaultflag means "use this value only if the variable hasn’t been defined yet"—it’s safe for overriding Bootstrap’s default without breaking other customizations.
- After defining this variable, import Bootstrap’s core SCSS file:
Adjust the path to match where Bootstrap is installed in your project (if using npm, it’s usually@import "path/to/bootstrap/scss/bootstrap";../node_modules/bootstrap/scss/bootstrap).
Step 3: Compile Your SCSS
Make sure your build tool (Webpack, Parcel, or even a simple SCSS compiler) is set up to turn your SCSS into CSS. Once compiled, your custom font will automatically apply to all Bootstrap components.
Why Your Earlier Attempt Didn’t Work
Bootstrap uses the $font-family-sans-serif variable directly in most component styles (e.g., .btn, .navbar). These styles have higher specificity than a basic body selector, so your body rule was overwritten. By changing the root variable, you’re telling Bootstrap to use your font everywhere it relies on the sans-serif family.
About Video Tutorials
You don’t need a video to get this working, but if you prefer visual walkthroughs, search for keywords like "Bootstrap SCSS change font family" on popular video platforms—you’ll find short, straightforward tutorials that walk through these exact steps.
内容的提问来源于stack exchange,提问作者Buckyx55

