Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Customizing with CSS variables

Bootstrap 5.3 keeps many of its values in CSS custom properties (you know them from the tutorial) prefixed with --bs-: the page background, the font, the border radius, button colors. If you override a variable in your own CSS, Bootstrap picks up the new value. Nothing has to be built: this works with a CDN too.

Where to write it

Your styles are loaded after Bootstrap. With a CDN that is a separate style.css file next to index.html and a <link href="style.css" rel="stylesheet"> line below the Bootstrap link. In a Vite project it is src/style.css, imported in main.js after Bootstrap.

/* style.css */
:root {
  --bs-body-font-family: Georgia, serif;
  --bs-border-radius: 1rem;
}

All page text switches to Georgia, and the rounding of buttons, cards and fields gets larger.

Global variables

They are declared on :root and apply to the whole page:

VariableWhat it sets
--bs-body-font-familyPage font
--bs-body-font-sizeBase text size
--bs-body-bg, --bs-body-colorPage background and text color
--bs-border-radiusRegular rounding
--bs-border-colorBorder color

In the preview the same can be shown with a <style> tag:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
  :root {
    --bs-body-bg: #fdf8f0;
    --bs-border-radius: 1rem;
  }
</style>
 
<div class="card" style="max-width: 18rem">
  <div class="card-body">
    <h5 class="card-title">Tasko</h5>
    <button type="button" class="btn btn-primary">Get started</button>
  </div>
</div>

The page background turned cream, and the corners of the card and button are noticeably rounder.

Component variables

Each component has its own variables: a button has --bs-btn-bg, --bs-btn-color, --bs-btn-hover-bg, a card has --bs-card-bg, --bs-card-border-color. They make it easy to create your own button variant:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
  .btn-brand {
    --bs-btn-color: #fff;
    --bs-btn-bg: #6f42c1;
    --bs-btn-border-color: #6f42c1;
    --bs-btn-hover-color: #fff;
    --bs-btn-hover-bg: #59359a;
    --bs-btn-hover-border-color: #59359a;
    --bs-btn-active-bg: #4d2e85;
  }
</style>
 
<button type="button" class="btn btn-brand">Brand button</button>

The btn class gives the button its shape, and btn-brand its purple colors. On hover the button darkens like the standard ones.

Common mistake

Changing --bs-primary and expecting all blue buttons to change color. Buttons and classes like bg-primary do not use this variable but their own: for btn-primary the color is in --bs-btn-bg, for bg-primary in --bs-primary-rgb. To change the main color everywhere at once, change the $primary variable in Sass — the next lesson.

Thanks for reading!

Donate to the site — we work hard for you.