Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override variables in Bootstrap 4 with another variable?

I am using Bootstrap 4 with SASS and I am questioning myself how to override a variable defined in Bootstrap's _variables.scss with another variable defined in that file.

From the Bootstrap website I learnt to first import my own overrides and then after that import the Bootstrap SASS files. So I did this:

@import 'modules/_overrides.scss';
@import 'vendor/_bootstrap.scss';

In my _overrides.scss I now want to override the body background color with the light gray variable $gray-200 defined in Bootstrap's variable file. However as I try accessing a variable before it has been defined I get an error.

After a lot of research I realized some people would get around that problem by copying the variables you want to override from Bootstrap's _variables.sccs and placing them at the top of your overrides file. However this seems like a very dirty way since the variables are now defined in multiple places.

So my question is: is there a way to override Bootstrap variables with another Bootstrap variable?

like image 697
Chris Avatar asked Oct 18 '22 01:10

Chris


1 Answers

I faced this same dilemma in a project recently. One way I found this to be a little less dirty is by giving the variable value after including both my overriding variables and Bootstrap's variables.

@import 'modules/_overrides.scss';
@import 'vendor/_bootstrap.scss';

$body-bg: $gray-light;

You could clean this up a little more by defining your own variables, independent of Bootstrap, at an earlier point and using those variables to give Bootstrap variables new values.

$myOwnGrayColor: #555;
@import 'modules/_overrides.scss';
//In _overrides.scss make something like $body-bg: $myOwnGrayColor; and $gray-light: $myOwnGrayColor;
@import 'vendor/_bootstrap.scss';

Since you cannot reference variables until they are defined, I'm afraid this is the only way to go.

like image 161
pentzzsolt Avatar answered Oct 21 '22 05:10

pentzzsolt