November 1, 2020
Bootstrap provides a ton of great utility classes for styling primary, danger, etc. but what if we want to support more themed colors? SASS to the rescue!
I had this same question, and ended up on this StackOverflow Question/Answer
https://stackoverflow.com/questions/38541526/adding-a-color-class-to-bootstrap/64637065
I have looked into Bootstrap, and noticed that there are few "color classes" included (primary, success, danger etc.) I would like to know if there is a way to add more classes like those mentioned in easy way.
For example: "primary" can be used with many elements, and will apply the defined color, and so does the other color classes. Can I create a class named "important", define its colors and apply it everywhere just like the included classes, without making a version of it for each element individually (using plain css or any of the preprocessors )
The main accepted answer suggests manually writing raw CSS to explicitly implement each new class yourself. This can work, and I've certainly used hacks like this myself on a variety of projects. However, there are obvious downsides to this approach, including duplicate code, manually calculating color codes for various states, and the dreaded !important
hammer!
css1@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css");23.important,4.important a {5 color: #fff !important;6 background-color: #ffc107 !important;7 border-color: #ff9800 !important;8}9.important:active,10.important.active,11.important:focus,12.important.focus,13.important:hover,14.important a:hover {15 background-color: #ff9800 !important;16 border-color: #ff5722 !important;17}
This is an older question but the accepted answer isn't the most complete and/or future-proof. Here's what I'd recommend if you've got SASS compilation as part of your build step.
For example, if you want to add a new "tertiary" color to the generated CSS classes, eg .text-tertiary
, .bg-tertiary
, .alert-tertiary
, etc. we can use the following steps:
.scss
file that will contain all of your SCSS and bootstrap overrides.styles.scss@import "_variables";@import "~bootstrap/scss/bootstrap.scss";
_variables.scss
file for your bootstrap variable configurations/overrides:_variables.scss1$tertiary: #218f8b;23// Add "tertiary" styles to the generated classes4$theme-colors: (5 "tertiary": $tertiary,6);
Further reading: See the official bootstrap documentation for more on theming: https://getbootstrap.com/docs/4.5/getting-started/theming/#add-to-map
Further reading...