Customizing Bootstrap 4

How to override variables in Bootstrap 4.

If you are moving from Bootstrap 3 to Bootstrap 4, you may suddenly have trouble defining your theme colors. This is because Bootstrap 3 traditionally used LESS and Bootstrap 4 now defaults to SASS.

Variables in SASS vs. LESS

Like LESS, SASS is a superset of CSS, in fact, a pre-processor of CSS, that is compiled and used to reduce duplication and make maintenance of CSS much easier. If you have been using LESS, you may already have installed a pre-processor which will also compile SASS. My favorite is Prepos, and it can be found at https://prepros.io/ for an unlimited free trial.

SASS is similar to LESS in many ways. For example, you can define a variable in LESS using an “@” and in SASS using a “$”.

LESS uses lazy evaluation

However, the big difference is in the properties of LESS variables. LESS uses lazy evaluation where you don’t need to define the variable before using it. For example:

@newcolor:#ff0000;
body {background-color:@newcolor;}
@newcolor:#0000ff;

This code will give a background color of blue, not red and the CSS will evaluate to:

body {background-color: #0000ff;

LESS looks forward and uses the last definition.

SASS does not use lazy evaluation

On the other hand, SASS will handle variables differently. For the same file snippet, replace the “@” with “$” and put the code in a SASS file like this:


$newcolor:#ff0000;
body {
background-color: $newcolor;
}
$newcolor:#0000ff;

The result is red, not blue. SASS does not look forward for another value of the variable. Here is the result:


body {
background-color: #ff0000;
}

Override the primary button background color in SASS

A common scenario is the need to override the primary color. Create your custom file with the following code.


@import "functions";
@import "mixins";
@import "variables";
$theme-colors: ( "primary": #00ff00 );
@import "bootstrap";

In the Html markup, add a button with the class “btn-primary”.


<button class="btn btn-primary"> this is a button</button>

This button will now appear green, not the default of blue. Here is the result.

.btn-primary {
background-color: #00ff00;
}

Notice that, in Bootstrap4, we set the theme colors using the theme-colors function. Setting the theme-colors function after importing bootstrap will have no effect. You will still get the default blue.

Learn more about theming bootstrap 4.

Posted in CSS

Leave a Reply

Your email address will not be published. Required fields are marked *