Theming Bootstrap
Customize Bootstrap 4 with our new built-in Sass variables for global style preferences for easy theming and component changes.
Introduction
In Bootstrap 3, theming was largely driven by variable overrides in LESS, custom CSS, and a separate theme stylesheet that we included in our dist files. With some effort, one could completely redesign the look of Bootstrap 3 without touching the core files. Bootstrap 4 provides a familiar, but slightly different approach.
Now, theming is accomplished by Sass variables, Sass maps, and custom CSS. There’s no more dedicated theme stylesheet; instead, you can enable the built-in theme to add gradients, shadows, and more.
Utilize our source Sass files to take advantage of variables, maps, mixins, and more.
File structure
Whenever possible, avoid modifying Bootstrap’s core files. For Sass, that means creating your own stylesheet that imports Bootstrap so you can modify and extend it. Assuming you’re using a package manager like npm, you’ll have a file structure that looks like this:
If you’ve downloaded our source files and aren’t using a package manager, you’ll want to manually setup something similar to that structure, keeping Bootstrap’s source files separate from your own.
Importing
In your custom.scss , you’ll import Bootstrap’s source Sass files. You have two options: include all of Bootstrap, or pick the parts you need. We encourage the latter, though be aware there are some requirements and dependencies across our components. You also will need to include some JavaScript for our plugins.
With that setup in place, you can begin to modify any of the Sass variables and maps in your custom.scss . You can also start to add parts of Bootstrap under the // Optional section as needed. We suggest using the full import stack from our bootstrap.scss file as your starting point.
Variable defaults
Every Sass variable in Bootstrap 4 includes the !default flag allowing you to override the variable’s default value in your own Sass without modifying Bootstrap’s source code. Copy and paste variables as needed, modify their values, and remove the !default flag. If a variable has already been assigned, then it won’t be re-assigned by the default values in Bootstrap.
Variable overrides within the same Sass file can come before or after the default variables. However, when overriding across Sass files, your overrides must come before you import Bootstrap’s Sass files.
Here’s an example that changes the background-color and color for the <body> when importing and compiling Bootstrap via npm:
Repeat as necessary for any variable in Bootstrap, including the global options below.
Maps and loops
Bootstrap 4 includes a handful of Sass maps, key value pairs that make it easier to generate families of related CSS. We use Sass maps for our colors, grid breakpoints, and more. Just like Sass variables, all Sass maps include the !default flag and can be overridden and extended.
Some of our Sass maps are merged into empty ones by default. This is done to allow easy expansion of a given Sass map, but comes at the cost of making removing items from a map slightly more difficult.
Modify map
To modify an existing color in our $theme-colors map, add the following to your custom Sass file:
Add to map
To add a new color to $theme-colors , add the new key and value:
Remove from map
To remove colors from $theme-colors , or any other map, use map-remove :
Required keys
Bootstrap assumes the presence of some specific keys within Sass maps as we used and extend these ourselves. As you customize the included maps, you may encounter errors where a specific Sass map’s key is being used.
For example, we use the primary , success , and danger keys from $theme-colors for links, buttons, and form states. Replacing the values of these keys should present no issues, but removing them may cause Sass compilation issues. In these instances, you’ll need to modify the Sass code that makes use of those values.
Functions
Bootstrap utilizes several Sass functions, but only a subset are applicable to general theming. We’ve included three functions for getting values from the color maps:
These allow you to pick one color from a Sass map much like how you’d use a color variable from v3.
We also have another function for getting a particular level of color from the $theme-colors map. Negative level values will lighten the color, while higher levels will darken.
In practice, you’d call the function and pass in two parameters: the name of the color from $theme-colors (e.g., primary or danger) and a numeric level.
Additional functions could be added in the future or your own custom Sass to create level functions for additional Sass maps, or even a generic one if you wanted to be more verbose.
Color contrast
One additional function we include in Bootstrap is the color contrast function, color-yiq . It utilizes the YIQ color space to automatically return a light ( #fff ) or dark ( #111 ) contrast color based on the specified base color. This function is especially useful for mixins or loops where you’re generating multiple classes.
For example, to generate color swatches from our $theme-colors map:
It can also be used for one-off contrast needs:
You can also specify a base color with our color map functions:
Sass options
Customize Bootstrap 4 with our built-in custom variables file and easily toggle global CSS preferences with new $enable-* Sass variables. Override a variable’s value and recompile with npm run test as needed.
You can find and customize these variables for key global options in our _variables.scss file.
| Variable | Values | Description |
|---|---|---|
| $spacer | 1rem (default), or any value > 0 | Specifies the default spacer value to programmatically generate our spacer utilities. |
| $enable-rounded | true (default) or false | Enables predefined border-radius styles on various components. |
| $enable-shadows | true or false (default) | Enables predefined box-shadow styles on various components. |
| $enable-gradients | true or false (default) | Enables predefined gradients via background-image styles on various components. |
| $enable-transitions | true (default) or false | Enables predefined transition s on various components. |
| $enable-hover-media-query | true or false (default) | Deprecated |
| $enable-grid-classes | true (default) or false | Enables the generation of CSS classes for the grid system (e.g., .container , .row , .col-md-1 , etc.). |
| $enable-caret | true (default) or false | Enables pseudo element caret on .dropdown-toggle . |
| $enable-print-styles | true (default) or false | Enables styles for optimizing printing. |
Color
Many of Bootstrap’s various components and utilities are built through a series of colors defined in a Sass map. This map can be looped over in Sass to quickly generate a series of rulesets.
How To Override Default Bootstrap CSS Styles
Developers often override or customize default Bootstrap CSS styles when working on web development projects. Most developers do it to make changes to Bootstrap fonts, borders, colors, or other bootstrap dashboard styles. In addition, default Bootstrap CSS styles are also customized to extend Bootstrap classes with new custom classes and to change Bootstrap grid layouts.
There are two easy and effective ways through which you can customize Bootstrap. Using CSS is the simplest and robust way to do so whereas using SASS for Bootstrap customization is actually an advanced method. Here you can find a step by step guide on how to customize Bootstrap with both of the above-mentioned methods.
Using CSS Override
CSS Customizations should be added to a separate custom.css file to ensure maintainability. This will guarantee that the original Bootstrap style files will remain unaltered.
You need to remember that order matters in CSS. So, the final definition of a particular CSS rule will override the previously defined rules when the CSS selectors & properties match. This is exactly why the custom.css reference should follow after Bootstrap.css.
Example
Bootstrap card component comes with a border by default. In this example, we will be removing the border and including a box-shadow to the Bootstrap card component by using custom.css. Here’s the code to do that.
The following image shows a default bootstrap card. 
Add the following lines of code in the custom.css file.
Here is an image of the resultant customized Bootstrap Card component
CSS Specificity
Another important point to keep in mind when overriding the bootstrap styles is CSS specificity. We will need to use selectors that are as specific as the ones in the bootstrap.css. Using selectors that are not specific will not give you desired results, as the component will end up taking the default bootstrap styles even though we have written the custom styles in custom.css file.
It is best to use CSS overrides for simple Bootstrap customizations, but we recommend you to try the SASS method when it comes to making extensive customizations.
Using SASS
SASS is the most recommended method to customize Bootstrap. This is mainly because SASS language is used to write the entire Bootstrap 4 CSS source.
A Project Structure will look like this.
In the Bootstrap SASS source file, you can find a Bootstrap.scss file that contains Bootstrap SASS files. There is also a variables.scss file, which contains all the SASS variables. You can use your custom.scss files to override these variables.
Bonus Read: Check out our entire range of bootstrap admin templates here.
Example
The first thing most developers do is to make adjustments to the color palette when customizing default Bootstrap styles. You will need to use $theme-colors SASS map to change the default colors. Here’s how you can change the colors in default Bootstrap theme-colors.
Import the bootstrap variables and functions into the custom.scss file. Now, add the code to change bootstrap default theme-colors and then add the bootstrap scss. The entire code in custom.scss is given below.
A default Bootstrap Button will look like this.

The button will look like this when it is customized by using the above-mentioned code.

New to Bootstrap? Check out our free tutorial on Bootstrap 4! If you’re interested in getting a Bootstrap admin template, we make the best! Check our website out.
Как переопределить CSS по умолчанию в Bootstrap

Разработчики часто переопределяют или настраивают стили css Bootstrap по умолчанию при работе над проектами веб-разработки. Большинство разработчиков делают это, чтобы внести изменения в шрифты Bootstrap, границы, цвета или другие стили Bootstrap. Кроме того, стили CSS Bootstrap по умолчанию также настраиваются для расширения классов Bootstrap новыми пользовательскими классами и изменения макетов сетки Bootstrap.
Есть два простых и эффективных способа, с помощью которых вы можете настроить Bootstrap. Использование CSS — это самый простой и надежный способ сделать это, в то время как использование SASS для настройки Bootstrap на самом деле является продвинутым методом. Здесь вы можете найти пошаговое руководство по настройке Bootstrap с помощью обоих вышеперечисленных методов.
Использование переопределения CSS
Настройки CSS должны быть добавлены в отдельный пользовательский custom.css файл для обеспечения удобства сопровождения. Это гарантирует, что исходные файлы стиля Bootstrap останутся неизменными.Вы должны помнить, что порядок имеет значение в CSS. Таким образом, окончательное определение конкретного правила CSS будет переопределять ранее определенные правила, когда CSS-селекторы и свойства совпадают. Именно поэтому таков custom.css ссылка должна следовать после bootstrap.css
Пример
Компонент Bootstrap card по умолчанию отображается с границей. В этом примере мы удалим границу и включим box-shadow в компонент Bootstrap card с помощью custom.css Там будет код который перекроет значения.На следующем рисунке показана загрузочная карта по умолчанию.

Добавьте следующие строки кода в пользовательский custom.css файл
Вот изображение и результат данного способа кастомизации компонента bootstrap карты

Специфика CSS
Еще один важный момент, который следует иметь в виду при переопределении стилей bootstrap — это специфика CSS. Нам нужно будет использовать селекторы, которые столь же специфичны, как и те, что находятся в bootstrap.css . Использование селекторов, которые не являются конкретными, не даст вам желаемых результатов, так как компонент в конечном итоге будет принимать стили начальной загрузки по умолчанию, даже если мы написали пользовательские стили в custom.css Лучше всего использовать переопределения CSS для простых настроек Bootstrap, но мы рекомендуем вам попробовать метод SASS, когда речь заходит о создании обширных настроек.
Использование SASS
SASS-это наиболее рекомендуемый метод настройки Bootstrap. Это происходит главным образом потому, что язык SASS используется для написания всего исходного кода CSS Bootstrap 4.Структура проекта будет выглядеть примерно так.
В исходном файле Bootstrap SASS вы можете найти bootstrap.scss файл, содержащий файлы Bootstrap SASS. Там же есть и variables.scss файл, содержащий все переменные SASS. Вы можете использовать свой custom.scss файл, чтобы переопределить эти переменные.
Пример
Первое, что делает большинство разработчиков, — это вносит коррективы в цветовую палитру при настройке стилей начальной загрузки по умолчанию. Вам нужно будет использовать $theme-colors SASS map, чтобы изменить цвета по умолчанию. Вот как вы можете изменить цвета в теме Bootstrap по цвета умолчанию.
По умолчанию цвета кнопок выглядят следующим образом

Теперь импортируйте переменные и функции bootstrap в пользовательский custom.scss . Теперь добавьте код для изменения цвета темы bootstrap по умолчанию, а затем добавьте bootstrap.scss . Весь код в custom.scss приведен ниже.
Кнопки по умолчанию будет выглядеть следующим образом.

Таким образом мы переопределили цвета по умолчанию. Этот способ также учтет новые цвета при наведении когда задается процент затемнения, который также можно переопределить. Но об этом уже в других статьях
Также у начинающего может возникнуть вопрос. А что со всем этим делать, после того как изменю sass файлы, где взять в итоге css?Если вы умеете работать с командной строкой, то можно посмотреть это видео:
Если с командной строкой есть сложности, то можно посмотреть видео с другим способом как собрать css
Как переопределять системные стили Bootstrap?
Нужна помощь. Возьмем частный случай. Bootstrap v4.0.0-beta.
Подключил я значит navbar:
В стилях по-умолчанию у класса .navbar идут отступы padding: .5rem 1rem; которые находятся в _navbar.scss:18 .
Собственно вопрос: как мне добавить / изменить / удалить эти отступы, не используя в созданном мною style.css правило !important? Можно как для чайника объяснить, так как в Saas и подобных вещах абсолютно не силен )
P.S. Не скачивать же исходники CSS и в них делать правки, как-то это не комильфо же совсем.
- Вопрос задан более трёх лет назад
- 12283 просмотра
- Вконтакте

Файлы бутстрапа не трогать.
Переопределить одиним из 2 методов:
1) Подключить свой css ниже бутстрапа, в нём написать например
Это переопределит отступы во всём бутстрапе
2) Добавить свой класс в конце:
Дальше делаете то же самое, в свой css ниже бутстрапа добавляете:
Это переопределит родные бутстраповские стили стили только в одном месте.
- Вконтакте


Метод хорош для простых ситуаций. Но в ситуациях посложнее, вероятно, всё-таки придется править и пересобирать SASS-исходники.
Пример из жизни: я хочу изменить цветовую гамму бутстрапа — ну вот эти все кнопочки и всё такое. Переопределить все цвета поверх — задолбаешься! Дело в том, что самих-то цветов там хоть и немного, но используются они в нескольких сотнях мест. И это не гипербола, реально несколько сотен. Разные элементы, да помножить на типы (primary, secondary, danger. ), да помножить на кучу состояний (hover, active, disabled, readonly. ) — это чокнуться можно.