Source

Theming Bootstrap

Yenza ngokwezifiso i-Bootstrap yesi-4 ngezinto zethu ezintsha ezakhelwe ngaphakathi ze-Sass zokhetho lwesitayile sehlabathi ukulungiselela umxholo olula kunye notshintsho lwamacandelo.

Intshayelelo

Kwi-Bootstrap 3, i-theming yayiqhutywa ubukhulu becala kukudlula okuguquguqukayo kwi-LESS, i-CSS yesiko, kunye necwecwe lesitayile somxholo owahlukileyo esiwufake distkwiifayile zethu. Ngomzamo othile, umntu unokuphinda ahlengahlengise ngokupheleleyo inkangeleko yeBootstrap 3 ngaphandle kokuchukumisa iifayile ezingundoqo. I-Bootstrap 4 ibonelela ngendlela eqhelekileyo, kodwa eyahlukileyo kancinane.

Ngoku, umxholo ufezekiswa ngoguquguquko lweSass, iimephu zeSass, kunye neCSS yesiko. Akusekho cwecwe lesimbo lomxholo ozinikeleyo; endaweni yoko, unokwenza umxholo owakhelwe-ngaphakathi ukongeza i-gradients, izithunzi, kunye nokunye.

Sass

Sebenzisa umthombo wethu weefayile zeSass ukuthatha ithuba lokuguquguquka, iimephu, imixube, kunye nokunye.

Ubume befayile

Nanini na kunokwenzeka, kunqanda ukulungisa iifayile ezingundoqo zeBootstrap. KwiSass, oko kuthetha ukwenza elakho iphepha lesimbo elingenisa ngaphandle iBootstrap ukuze ukwazi ukuyilungisa kwaye uyandise. Ucinga ukuba usebenzisa umphathi wephakheji njenge-npm, uya kuba nesakhiwo sefayile esijongeka ngolu hlobo:

your-project/
├── scss
│   └── custom.scss
└── node_modules/
    └── bootstrap
        ├── js
        └── scss

Ukuba ukhuphele iifayile zethu zemvelaphi kwaye awusebenzisi umphathi wepakethe, uya kufuna ukuseta ngesandla into efana neso sakhiwo, ugcine iifayile zemvelaphi yeBootstrap zahlukile kweyakho.

your-project/
├── scss
│   └── custom.scss
└── bootstrap/
    ├── js
    └── scss

Ukungenisa elizweni

Kweyakho custom.scss, uya kungenisa iifayile zeSass zomthombo weBootstrap. Uneendlela ezimbini ongakhetha kuzo: bandakanya yonke iBootstrap, okanye khetha iindawo ozifunayo. Siyayikhuthaza le yokugqibela, nangona sisazi ukuba kukho iimfuno kunye nokuxhomekeka kumacandelo ethu. Kananjalo kuya kufuneka ubandakanye iJavaScript yeeplagi zethu.

// Custom.scss
// Option A: Include all of Bootstrap

@import "../node_modules/bootstrap/scss/bootstrap";
// Custom.scss
// Option B: Include parts of Bootstrap

// Required
@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/mixins";

// Optional
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
@import "../node_modules/bootstrap/scss/images";
@import "../node_modules/bootstrap/scss/code";
@import "../node_modules/bootstrap/scss/grid";

Ngolu seto lusendaweni, ungaqala ukulungisa naziphi na izinto eziguquguqukayo zeSass kunye neemephu kweyakho custom.scss. Ungaqalisa kwakhona ukongeza iinxalenye zeBootstrap phantsi // Optionalkwecandelo njengoko kufuneka. Sicebisa ukuba usebenzise isitaki esipheleleyo sokungenisa bootstrap.scsskwifayile yethu njengendawo yakho yokuqala.

Ukungagqibeki okuguquguqukayo

Yonke into eguquguqukayo ye-Sass kwi-Bootstrap 4 ibandakanya !defaultiflegi ekuvumela ukuba ubhale ngaphezulu ixabiso elimiselweyo le-Sass yakho ngaphandle kokuguqula ikhowudi yemvelaphi ye-Bootstrap. Khuphela kwaye uncamathisele izinto eziguquguqukayo njengoko kufuneka, uguqule amaxabiso azo, kwaye ususe !defaultiflegi. Ukuba uguqulo sele lwabelwe, ngoko aluzukwabelwa kwakhona ngamaxabiso angagqibekanga kwiBootstrap.

Uya kufumana uluhlu olupheleleyo lweenguqu zeBootstrap kwi scss/_variables.scss.

Ukugqithisa okuguquguqukayo ngaphakathi kwefayile ye-Sass efanayo kunokuza ngaphambi okanye emva kokuguquguquka okungagqibekanga. Nangona kunjalo, xa ubeka ngaphezulu kwiifayile zeSass, izinto zakho ezingaphezulu kufuneka zize phambi kokuba ungenise iifayile zeSass zeBootstrap.

Nanku umzekelo otshintsha background-colorkunye colorneyokurhweba <body>ngaphandle kunye nokuqulunqa i-Bootstrap nge-npm:

// Your variable overrides
$body-bg: #000;
$body-color: #111;

// Bootstrap and its default variables
@import "../node_modules/bootstrap/scss/bootstrap";

Phinda njengoko kuyimfuneko kuyo nayiphi na inguqu kwiBootstrap, kuquka iinketho zehlabathi ezingezantsi.

Iimephu kunye neelophu

I-Bootstrap 4 ibandakanya iimephu ze-Sass ezimbalwa, izibini zexabiso eziphambili ezenza kube lula ukuvelisa iintsapho ze-CSS ehambelanayo. Sisebenzisa iimephu zakwaSass kwimibala yethu, iindawo zokuqhawula igridi, nokunye. Kanye njengezinto eziguquguqukayo ze-Sass, zonke iimephu ze-Sass zibandakanya !defaultiflegi kwaye zinokubhalwa ngaphezulu kwaye zandiswe.

Ezinye zeemephu zethu zakwaSass zidityaniswa zibe zingenanto ngokungagqibekanga. Oku kwenzelwa ukuvumela ukwandiswa lula kwemephu ye-Sass enikiweyo, kodwa kuza ngexabiso lokwenza ukususa izinto kwimephu kube nzima ngakumbi.

Guqula imephu

Ukuguqula umbala osele ukhona $theme-colorskwimephu yethu, yongeza oku kulandelayo kwifayile yakho yesiko leSass:

$theme-colors: (
  "primary": #0074d9,
  "danger": #ff4136
);

Yongeza kwimephu

Ukongeza umbala omtsha $theme-colors, yongeza iqhosha elitsha kunye nexabiso:

$theme-colors: (
  "custom-color": #900
);

Susa kwimephu

Ukususa imibala kwi- $theme-colors, okanye nayiphi na enye imephu, sebenzisa map-remove. Qaphela ukuba kufuneka uyifake phakathi kweemfuno zethu kunye nokhetho:

// Required
@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/mixins";

$theme-colors: map-remove($theme-colors, "info", "light", "dark");

// Optional
@import "../node_modules/bootstrap/scss/root";
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
...

Izitshixo ezifunekayo

I-Bootstrap ithatha ubukho bezitshixo ezithile ngaphakathi kweemephu ze-Sass njengoko besizisebenzisa kwaye sizandise ngokwethu. Njengoko ulungiselela iimephu ezibandakanyiweyo, ungadibana neempazamo apho kusetyenziswa isitshixo semephu ye-Sass ethile.

Umzekelo, sisebenzisa i- primary, successkunye dangernezitshixo ezisuka $theme-colorskumakhonkco, amaqhosha, kunye nefom yesimo. Ukutshintsha amaxabiso ezi zitshixo kufuneka kungabikho miba, kodwa ukuwasusa kunokubangela imiba yokuhlanganiswa kwe-Sass. Kwezi meko, kuya kufuneka uguqule ikhowudi ye-Sass esebenzisa loo maxabiso.

Imisebenzi

I-Bootstrap isebenzisa imisebenzi emininzi ye-Sass, kodwa iseti encinci kuphela esebenzayo kumxholo jikelele. Sifake imisebenzi emithathu yokufumana ixabiso kwiimephu zemibala:

@function color($key: "blue") {
  @return map-get($colors, $key);
}

@function theme-color($key: "primary") {
  @return map-get($theme-colors, $key);
}

@function gray($key: "100") {
  @return map-get($grays, $key);
}

Oku kukuvumela ukuba ukhethe umbala omnye kwimephu ye-Sass ngendlela onokuthi usebenzise ngayo ukuguquguquka kombala ukusuka kwi-v3.

.custom-element {
  color: gray("100");
  background-color: theme-color("dark");
}

Kananjalo sinomnye umsebenzi wokufumana umgangatho othile wombala kwimephu $theme-colors. Amaxabiso amanqanaba angalunganga aya kuwenza lula umbala, ngelixa amanqanaba aphezulu aya kuba mnyama.

@function theme-color-level($color-name: "primary", $level: 0) {
  $color: theme-color($color-name);
  $color-base: if($level > 0, #000, #fff);
  $level: abs($level);

  @return mix($color-base, $color, $level * $theme-color-interval);
}

Ngokwenza, ungabiza umsebenzi kwaye ugqithise kwiiparamitha ezimbini: igama lombala ukusuka $theme-colors(umzekelo, iprimary okanye ingozi) kunye nenqanaba lamanani.

.custom-element {
  color: theme-color-level(primary, -10);
}

Imisebenzi eyongezelelweyo inokongezwa kwixesha elizayo okanye i-Sass yakho yesiko ukwenza imisebenzi yenqanaba leemephu ze-Sass ezongezelelweyo, okanye enye yegeneric ukuba ufuna ukuba ne-verbose ngakumbi.

Umahluko wombala

Omnye umsebenzi owongezelelweyo esiwufakayo kwiBootstrap ngumsebenzi wokuchasa umbala, color-yiq. Isebenzisa isithuba sombala we-YIQ ukubuyisela ngokuzenzekelayo ukukhanya ( #fff) okanye mnyama ( #111) umahluko wombala osekelwe kumbala wesiseko oxeliweyo. Lo msebenzi uluncedo kakhulu kwimixube okanye iilophu apho uvelisa iiklasi ezininzi.

Umzekelo, ukuvelisa iiwotshi zemibala $theme-colorskwimephu yethu:

@each $color, $value in $theme-colors {
  .swatch-#{$color} {
    color: color-yiq($value);
  }
}

Ingasetyenziselwa iimfuno zokuthelekisa enye:

.custom-element {
  color: color-yiq(#000); // returns `color: #fff`
}

You can also specify a base color with our color map functions:

.custom-element {
  color: color-yiq(theme-color("dark")); // returns `color: #fff`
}

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 Bootstrap’s scss/_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 transitions 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.

All colors

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 we already include.

Blue
Indigo
Purple
Pink
Red
Orange
Yellow
Green
Teal
Cyan

Here’s how you can use these in your Sass:

// With variable
.alpha { color: $purple; }

// From the Sass map with our `color()` function
.beta { color: color("purple"); }

Color utility classes are also available for setting color and background-color.

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.

Theme colors

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.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

Grays

An expansive set of gray variables and a Sass map in scss/_variables.scss for consistent shades of gray across your project.

100
200
300
400
500
600
700
800
900

Within scss/_variables.scss, you’ll find Bootstrap’s color variables and Sass map. Here’s an example of the $colors Sass map:

$colors: (
  "blue": $blue,
  "indigo": $indigo,
  "purple": $purple,
  "pink": $pink,
  "red": $red,
  "orange": $orange,
  "yellow": $yellow,
  "green": $green,
  "teal": $teal,
  "cyan": $cyan,
  "white": $white,
  "gray": $gray-600,
  "gray-dark": $gray-800
) !default;

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.

Components

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.

Modifiers

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.

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.

// Generate alert modifier classes
@each $color, $value in $theme-colors {
  .alert-#{$color} {
    @include alert-variant(theme-color-level($color, -10), theme-color-level($color, -9), theme-color-level($color, 6));
  }
}

// Generate `.bg-*` color utilities
@each $color, $value in $theme-colors {
  @include bg-variant('.bg-#{$color}', $value);
}

Responsive

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.

@each $breakpoint in map-keys($grid-breakpoints) {
  @include media-breakpoint-up($breakpoint) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    .text#{$infix}-left   { text-align: left !important; }
    .text#{$infix}-right  { text-align: right !important; }
    .text#{$infix}-center { text-align: center !important; }
  }
}

Should you need to modify your $grid-breakpoints, your changes will apply to all the loops iterating over that map.

CSS variables

Bootstrap 4 includes around two dozen CSS custom properties (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.

Available variables

Here are the variables we include (note that the :root is required). They’re located in our _root.scss file.

:root {
  --blue: #007bff;
  --indigo: #6610f2;
  --purple: #6f42c1;
  --pink: #e83e8c;
  --red: #dc3545;
  --orange: #fd7e14;
  --yellow: #ffc107;
  --green: #28a745;
  --teal: #20c997;
  --cyan: #17a2b8;
  --white: #fff;
  --gray: #6c757d;
  --gray-dark: #343a40;
  --primary: #007bff;
  --secondary: #6c757d;
  --success: #28a745;
  --info: #17a2b8;
  --warning: #ffc107;
  --danger: #dc3545;
  --light: #f8f9fa;
  --dark: #343a40;
  --breakpoint-xs: 0;
  --breakpoint-sm: 576px;
  --breakpoint-md: 768px;
  --breakpoint-lg: 992px;
  --breakpoint-xl: 1200px;
  --font-family-sans-serif: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  --font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}

Examples

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.

body {
  font: 1rem/1.5 var(--font-family-sans-serif);
}
a {
  color: var(--blue);
}

Breakpoint variables

Ngelixa ekuqaleni sasibandakanya ii-breakpoints kwiinguqu zethu ze-CSS (umzekelo, --breakpoint-md), ezi azixhaswanga kwimibuzo yemidiya , kodwa zisenokusetyenziswa ngaphakathi kweesethi zomthetho kwimibuzo yemidiya. Ezi zantlukwano zebreakpoint zihlala kwi-CSS ehlanganisiweyo yokuhambelana ngasemva xa zinokuthi zisetyenziswe yiJavaScript. Funda ngakumbi kwi-spec.

Nanku umzekelo wento engaxhaswayo:

@media (min-width: var(--breakpoint-sm)) {
  ...
}

Kwaye nanku umzekelo wento exhaswayo:

@media (min-width: 768px) {
  .custom-element {
    color: var(--primary);
  }
}