Stripped personal data from development repository
Samo Penic
2019-02-20 83c3f647c35477564b77cbc5b36d37d793d5442a
commit | author | age
83c3f6 1 ---
SP 2 layout: docs
3 title: Theming Bootstrap
4 description: Customize Bootstrap 4 with our new built-in Sass variables for global style preferences for easy theming and component changes.
5 group: getting-started
6 toc: true
7 ---
8
9 ## Introduction
10
11 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.
12
13 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.
14
15 ## Sass
16
17 Utilize our source Sass files to take advantage of variables, maps, mixins, and more. In our build we've increased the Sass rounding precision to 6 (by default it's 5) to prevent issues with browser rounding.
18
19 ### File structure
20
21 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:
22
23 {% highlight plaintext %}
24 your-project/
25 ├── scss
26 │   └── custom.scss
27 └── node_modules/
28     └── bootstrap
29         ├── js
30         └── scss
31 {% endhighlight %}
32
33 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.
34
35 {% highlight plaintext %}
36 your-project/
37 ├── scss
38 │   └── custom.scss
39 └── bootstrap/
40     ├── js
41     └── scss
42 {% endhighlight %}
43
44 ### Importing
45
46 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.
47
48 {% highlight scss %}
49 // Custom.scss
50 // Option A: Include all of Bootstrap
51
52 @import "../node_modules/bootstrap/scss/bootstrap";
53 {% endhighlight %}
54
55 {% highlight scss %}
56 // Custom.scss
57 // Option B: Include parts of Bootstrap
58
59 // Required
60 @import "../node_modules/bootstrap/scss/functions";
61 @import "../node_modules/bootstrap/scss/variables";
62 @import "../node_modules/bootstrap/scss/mixins";
63
64 // Optional
65 @import "../node_modules/bootstrap/scss/reboot";
66 @import "../node_modules/bootstrap/scss/type";
67 @import "../node_modules/bootstrap/scss/images";
68 @import "../node_modules/bootstrap/scss/code";
69 @import "../node_modules/bootstrap/scss/grid";
70 {% endhighlight %}
71
72 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.
73
74 ### Variable defaults
75
76 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.
77
78 You will find the complete list of Bootstrap's variables in `scss/_variables.scss`.
79
80 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.
81
82 Here's an example that changes the `background-color` and `color` for the `<body>` when importing and compiling Bootstrap via npm:
83
84 {% highlight scss %}
85 // Your variable overrides
86 $body-bg: #000;
87 $body-color: #111;
88
89 // Bootstrap and its default variables
90 @import "../node_modules/bootstrap/scss/bootstrap";
91 {% endhighlight %}
92
93 Repeat as necessary for any variable in Bootstrap, including the global options below.
94
95 ### Maps and loops
96
97 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.
98
99 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.
100
101 #### Modify map
102
103 To modify an existing color in our `$theme-colors` map, add the following to your custom Sass file:
104
105 {% highlight scss %}
106 $theme-colors: (
107   "primary": #0074d9,
108   "danger": #ff4136
109 );
110 {% endhighlight %}
111
112 #### Add to map
113
114 To add a new color to `$theme-colors`, add the new key and value:
115
116 {% highlight scss %}
117 $theme-colors: (
118   "custom-color": #900
119 );
120 {% endhighlight %}
121
122 #### Remove from map
123
124 To remove colors from `$theme-colors`, or any other map, use `map-remove`. Be aware you must insert it between our requirements and options:
125
126 {% highlight scss %}
127 // Required
128 @import "../node_modules/bootstrap/scss/functions";
129 @import "../node_modules/bootstrap/scss/variables";
130 @import "../node_modules/bootstrap/scss/mixins";
131
132 $theme-colors: map-remove($theme-colors, "info", "light", "dark");
133
134 // Optional
135 @import "../node_modules/bootstrap/scss/root";
136 @import "../node_modules/bootstrap/scss/reboot";
137 @import "../node_modules/bootstrap/scss/type";
138 ...
139 {% endhighlight %}
140
141 #### Required keys
142
143 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.
144
145 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.
146
147 ### Functions
148
149 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:
150
151 {% highlight scss %}
152 @function color($key: "blue") {
153   @return map-get($colors, $key);
154 }
155
156 @function theme-color($key: "primary") {
157   @return map-get($theme-colors, $key);
158 }
159
160 @function gray($key: "100") {
161   @return map-get($grays, $key);
162 }
163 {% endhighlight %}
164
165 These allow you to pick one color from a Sass map much like how you'd use a color variable from v3.
166
167 {% highlight scss %}
168 .custom-element {
169   color: gray("100");
170   background-color: theme-color("dark");
171 }
172 {% endhighlight %}
173
174 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.
175
176 {% highlight scss %}
177 @function theme-color-level($color-name: "primary", $level: 0) {
178   $color: theme-color($color-name);
179   $color-base: if($level > 0, #000, #fff);
180   $level: abs($level);
181
182   @return mix($color-base, $color, $level * $theme-color-interval);
183 }
184 {% endhighlight %}
185
186 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.
187
188 {% highlight scss %}
189 .custom-element {
190   color: theme-color-level(primary, -10);
191 }
192 {% endhighlight %}
193
194 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.
195
196 ### Color contrast
197
198 One additional function we include in Bootstrap is the color contrast function, `color-yiq`. It utilizes the [YIQ color space](https://en.wikipedia.org/wiki/YIQ) 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.
199
200 For example, to generate color swatches from our `$theme-colors` map:
201
202 {% highlight scss %}
203 @each $color, $value in $theme-colors {
204   .swatch-#{$color} {
205     color: color-yiq($value);
206   }
207 }
208 {% endhighlight %}
209
210 It can also be used for one-off contrast needs:
211
212 {% highlight scss %}
213 .custom-element {
214   color: color-yiq(#000); // returns `color: #fff`
215 }
216 {% endhighlight %}
217
218 You can also specify a base color with our color map functions:
219
220 {% highlight scss %}
221 .custom-element {
222   color: color-yiq(theme-color("dark")); // returns `color: #fff`
223 }
224 {% endhighlight %}
225
226 ## Sass options
227
228 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.
229
230 You can find and customize these variables for key global options in Bootstrap's `scss/_variables.scss` file.
231
232 | Variable                    | Values                             | Description                                                                            |
233 | --------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------- |
234 | `$spacer`                   | `1rem` (default), or any value > 0 | Specifies the default spacer value to programmatically generate our [spacer utilities]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/spacing/). |
235 | `$enable-rounded`           | `true` (default) or `false`        | Enables predefined `border-radius` styles on various components. |
236 | `$enable-shadows`           | `true` or `false` (default)        | Enables predefined `box-shadow` styles on various components. |
237 | `$enable-gradients`         | `true` or `false` (default)        | Enables predefined gradients via `background-image` styles on various components. |
238 | `$enable-transitions`       | `true` (default) or `false`        | Enables predefined `transition`s on various components. |
239 | `$enable-prefers-reduced-motion-media-query`       | `true` (default) or `false`        | Enables the [`prefers-reduced-motion` media query]({{ site.baseurl }}/docs/{{ site.docs_version }}/getting-started/accessibility/#reduced-motion), which suppresses certain animations/transitions based on the users' browser/operating system preferences. |
240 | `$enable-hover-media-query` | `true` or `false` (default)        | **Deprecated** |
241 | `$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.). |
242 | `$enable-caret`             | `true` (default) or `false`        | Enables pseudo element caret on `.dropdown-toggle`. |
243 | `$enable-print-styles`      | `true` (default) or `false`        | Enables styles for optimizing printing. |
244 | `$enable-validation-icons`  | `true` (default) or `false`        | Enables `background-image` icons within textual inputs and some custom forms for validation states. |
245
246 ## Color
247
248 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.
249
250 ### All colors
251
252 All colors available in Bootstrap 4, are available as Sass variables and a Sass map in `scss/_variables.scss` file. This will be expanded upon in subsequent minor releases to add additional shades, much like the [grayscale palette](#grays) we already include.
253
254 <div class="row">
255   {% for color in site.data.colors %}
256     {% unless color.name == "white" or color.name == "gray" or color.name == "gray-dark" %}
257     <div class="col-md-4">
258         <div class="p-3 mb-3 swatch-{{ color.name }}">{{ color.name | capitalize }}</div>
259     </div>
260     {% endunless %}
261   {% endfor %}
262 </div>
263
264 Here's how you can use these in your Sass:
265
266 {% highlight scss %}
267 // With variable
268 .alpha { color: $purple; }
269
270 // From the Sass map with our `color()` function
271 .beta { color: color("purple"); }
272 {% endhighlight %}
273
274 [Color utility classes]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/colors/) are also available for setting `color` and `background-color`.
275
276 {% capture callout %}
277 In the future, we'll aim to provide Sass maps and variables for shades of each color as we've done with the grayscale colors below.
278 {% endcapture %}
279 {% include callout.html content=callout type="info" %}
280
281 ### Theme colors
282
283 We use a subset of all colors to create a smaller color palette for generating color schemes, also available as Sass variables and a Sass map in Bootstraps's `scss/_variables.scss` file.
284
285 <div class="row">
286   {% for color in site.data.theme-colors %}
287     <div class="col-md-4">
288       <div class="p-3 mb-3 swatch-{{ color.name }}">{{ color.name | capitalize }}</div>
289     </div>
290   {% endfor %}
291 </div>
292
293 ### Grays
294
295 An expansive set of gray variables and a Sass map in `scss/_variables.scss` for consistent shades of gray across your project. Note that these are "cool grays", which tend towards a subtle blue tone, rather than neutral grays.
296
297 <div class="row mb-3">
298   <div class="col-md-4">
299     {% for color in site.data.grays %}
300       <div class="p-3 swatch-{{ color.name }}">{{ color.name | capitalize }}</div>
301     {% endfor %}
302   </div>
303 </div>
304
305 Within `scss/_variables.scss`, you'll find Bootstrap's color variables and Sass map. Here's an example of the `$colors` Sass map:
306
307 {% highlight scss %}
308 $colors: (
309   "blue": $blue,
310   "indigo": $indigo,
311   "purple": $purple,
312   "pink": $pink,
313   "red": $red,
314   "orange": $orange,
315   "yellow": $yellow,
316   "green": $green,
317   "teal": $teal,
318   "cyan": $cyan,
319   "white": $white,
320   "gray": $gray-600,
321   "gray-dark": $gray-800
322 ) !default;
323 {% endhighlight %}
324
325 Add, remove, or modify values within the map to update how they're used in many other components. Unfortunately at this time, not _every_ component utilizes this Sass map. Future updates will strive to improve upon this. Until then, plan on making use of the `${color}` variables and this Sass map.
326
327 ## Components
328
329 Many of Bootstrap's components and utilities are built with `@each` loops that iterate over a Sass map. This is especially helpful for generating variants of a component by our `$theme-colors` and creating responsive variants for each breakpoint. As you customize these Sass maps and recompile, you'll automatically see your changes reflected in these loops.
330
331 ### Modifiers
332
333 Many of Bootstrap's components are built with a base-modifier class approach. This means the bulk of the styling is contained to a base class (e.g., `.btn`) while style variations are confined to modifier classes (e.g., `.btn-danger`). These modifier classes are built from the `$theme-colors` map to make customizing the number and name of our modifier classes.
334
335 Here are two examples of how we loop over the `$theme-colors` map to generate modifiers to the `.alert` component and all our `.bg-*` background utilities.
336
337 {% highlight scss %}
338 // Generate alert modifier classes
339 @each $color, $value in $theme-colors {
340   .alert-#{$color} {
341     @include alert-variant(theme-color-level($color, -10), theme-color-level($color, -9), theme-color-level($color, 6));
342   }
343 }
344
345 // Generate `.bg-*` color utilities
346 @each $color, $value in $theme-colors {
347   @include bg-variant('.bg-#{$color}', $value);
348 }
349 {% endhighlight %}
350
351 ### Responsive
352
353 These Sass loops aren't limited to color maps, either. You can also generate responsive variations of your components or utilities. Take for example our responsive text alignment utilities where we mix an `@each` loop for the `$grid-breakpoints` Sass map with a media query include.
354
355 {% highlight scss %}
356 @each $breakpoint in map-keys($grid-breakpoints) {
357   @include media-breakpoint-up($breakpoint) {
358     $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
359
360     .text#{$infix}-left   { text-align: left !important; }
361     .text#{$infix}-right  { text-align: right !important; }
362     .text#{$infix}-center { text-align: center !important; }
363   }
364 }
365 {% endhighlight %}
366
367 Should you need to modify your `$grid-breakpoints`, your changes will apply to all the loops iterating over that map.
368
369 ## CSS variables
370
371 Bootstrap 4 includes around two dozen [CSS custom properties (variables)](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables) in its compiled CSS. These provide easy access to commonly used values like our theme colors, breakpoints, and primary font stacks when working in your browser's Inspector, a code sandbox, or general prototyping.
372
373 ### Available variables
374
375 Here are the variables we include (note that the `:root` is required). They're located in our `_root.scss` file.
376
377 {% highlight css %}
378 :root {
379   --blue: #007bff;
380   --indigo: #6610f2;
381   --purple: #6f42c1;
382   --pink: #e83e8c;
383   --red: #dc3545;
384   --orange: #fd7e14;
385   --yellow: #ffc107;
386   --green: #28a745;
387   --teal: #20c997;
388   --cyan: #17a2b8;
389   --white: #fff;
390   --gray: #6c757d;
391   --gray-dark: #343a40;
392   --primary: #007bff;
393   --secondary: #6c757d;
394   --success: #28a745;
395   --info: #17a2b8;
396   --warning: #ffc107;
397   --danger: #dc3545;
398   --light: #f8f9fa;
399   --dark: #343a40;
400   --breakpoint-xs: 0;
401   --breakpoint-sm: 576px;
402   --breakpoint-md: 768px;
403   --breakpoint-lg: 992px;
404   --breakpoint-xl: 1200px;
405   --font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
406   --font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
407 }
408 {% endhighlight %}
409
410 ### Examples
411
412 CSS variables offer similar flexibility to Sass's variables, but without the need for compilation before being served to the browser. For example, here we're resetting our page's font and link styles with CSS variables.
413
414 {% highlight css %}
415 body {
416   font: 1rem/1.5 var(--font-family-sans-serif);
417 }
418 a {
419   color: var(--blue);
420 }
421 {% endhighlight %}
422
423 ### Breakpoint variables
424
425 While we originally included breakpoints in our CSS variables (e.g., `--breakpoint-md`), **these are not supported in media queries**, but they can still be used _within_ rulesets in media queries. These breakpoint variables remain in the compiled CSS for backward compatibility given they can be utilized by JavaScript. [Learn more in the spec](https://www.w3.org/TR/css-variables-1/#using-variables).
426
427 Here's an example of **what's not supported:**
428
429 {% highlight css %}
430 @media (min-width: var(--breakpoint-sm)) {
431   ...
432 }
433 {% endhighlight %}
434
435 And here's an example of **what is supported:**
436
437 {% highlight css %}
438 @media (min-width: 768px) {
439   .custom-element {
440     color: var(--primary);
441   }
442 }
443 {% endhighlight %}