Source

Motó ya likambo Bootstrap

Personnaliser Bootstrap 4 na ba variables na biso ya sika ya Sass oyo etongami na kati mpo na ba préférences ya style mondial mpo na thème ya pete mpe ba changements ya composant.

Maloba ya ebandeli

Na Bootstrap 3, thème ezalaki mingi mingi kokambama na ba overrides ya variable na LESS, CSS personnalisé, mpe stylesheet ya thème ekeseni oyo tokɔtisaki na ba distfichiers na biso. Na mwa milende, moto akokaki kobongola mobimba lolenge ya komonana ya Bootstrap 3 kozanga kosimba ba fichiers ya moboko. Bootstrap 4 epesaka ndenge oyo eyebani, kasi oyo ekeseni mwa moke.

Sikoyo, thème ekokisami na ba variables ya Sass, ba cartes ya Sass, na CSS personnalisé. Ezali na feuille de style ya thème oyo epesameli lisusu te; na esika na yango, okoki kopesa nzela na motó ya likambo oyo etongami mpo na kobakisa ba gradients, bilili, mpe makambo mosusu.

Sass oyo azali

Salelá ba fichiers na biso ya Sass ya source mpo na ko profiter na ba variables, ba cartes, ba mixins, mpe mingi mosusu. Na kotonga na biso tomatisaki précision ya arrondissement ya Sass na 6 (par défaut ezali 5) pona kopekisa ba problèmes na arrondissement ya navigateur.

Bokeli ya fisyé

Soki likoki ezali, koboya kobongola ba fichiers ya moboko ya Bootstrap. Mpo na Sass, yango elingi koloba kosala stylesheet na yo moko oyo ekotisaka Bootstrap mpo ete okoka ko modifier mpe ko extend yango. Soki tokanisi ete ozali kosalela mokambi ya ba paquets lokola npm, okozala na ebongiseli ya fisyé oyo ezali lokola oyo:

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

Soki o téléchargé ba fichiers source na biso mpe ozali kosalela gestionnaire ya ba paquets te, okolinga ko configurer manuellement eloko moko ya ndenge moko na structure wana, kobatela ba fichiers source ya Bootstrap separate na oyo ya yo.

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

Kokɔtisa biloko na mboka mopaya

Na custom.scss, oko kotisa ba fichiers Sass ya source ya Bootstrap. Ozali na ba options mibale: kotia nionso ya Bootstrap, to pona ba parties oyo osengeli na yango. Tolendisi oyo ya nsuka, atako yeba ete ezali na mwa masengi mpe bozangi boyokani na kati ya biteni na biso. Okozala mpe na mposa ya kotya mwa JavaScript mpo na ba plugins na biso.

// 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";

Na setup wana na esika, okoki kobanda ko modifier moko ya ba variables ya Sass na ba cartes na yo custom.scss. Okoki mpe kobanda kobakisa biteni ya Bootstrap na nse ya // Optionaleteni soki esengeli. Tosengi kosalela stack ya importation mobimba uta na bootstrap.scssfichier na biso lokola point de départ na yo.

Ba défauts ya variable

Variable nionso ya Sass na Bootstrap 4 ezali na !defaultdrapeau oyo epesaka yo nzela ya ko superposer valeur par défaut ya variable na Sass na yo moko sans ko modifier code source ya Bootstrap. Copier pe coller ba variables soki esengeli, modifier ba valeurs na yango, pe longola !defaultdrapeau. Soki variable moko esi epesameli, wana ekopesama lisusu te na ba valeurs par défaut na Bootstrap.

Okokuta liste mobimba ya ba variables ya Bootstrap na scss/_variables.scss.

Ba overrides ya variable na kati ya fichier Sass moko ekoki koya avant to sima ya ba variables par défaut. Kasi, tango ozali ko overrider na kati ya ba fichiers Sass, ba overrides na yo esengeli eya liboso ya ko kotisa ba fichiers Sass ya Bootstrap.

Tala ndakisa oyo ebongoli background-colormpe colormpo na <body>ntango ya kokɔtisa mpe kosangisa Bootstrap na nzela ya npm:

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

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

Zongela soki esengeli mpo na variable nyonso na Bootstrap, bakisa mpe ba options ya mokili mobimba oyo ezali awa na nse.

Bakarte mpe ba boucles

Bootstrap 4 ezali na mwa ndambo ya ba cartes ya Sass, ba paires ya valeur clé oyo esalaka ete ezala pete mpo na kobimisa mabota ya CSS oyo ezali na boyokani. Tosalelaka ba cartes ya Sass pona ba couleurs na biso, ba points de rupture ya grille, pe ebele. Kaka lokola ba variables ya Sass, ba cartes nionso ya Sass ezali na !defaultdrapeau mpe ekoki kozala surpassé mpe ko extend.

Ba cartes na biso misusu ya Sass esangani na oyo ya pamba par défaut. Yango esalemaka mpo na kopesa nzela na bopanzani ya pete ya karte ya Sass oyo epesami, kasi eyaka na ntalo ya kosala ete kolongola biloko na karte ezala mwa mpasi mingi.

Bobongola karte

Mpo na kobongola langi oyo ezali na $theme-colorskarte na biso, bakisá makambo oyo elandi na fisyé na yo ya Sass oyo olingi:

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

Bakisa na karte

Mpo na kobakisa langi ya sika na $theme-colors, bakisá fungola mpe motuya ya sika:

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

Longola yango na karte

Mpo na kolongola balangi na $theme-colors, to na karte mosusu nyonso, salelá map-remove. Yeba ete osengeli kokotisa yango kati na masengi mpe banzela na biso:

// 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";
...

Bafungola oyo esengeli

Bootstrap ezuaka présence ya ba touches spécifiques mosusu na kati ya ba cartes ya Sass ndenge tosalelaki mpe to extend oyo biso moko. Ntango ozali kobongisa bakarte oyo ezali na kati, okoki kokutana na mabunga esika oyo ezali kosalela fungola ya karte ya Sass moko boye.

Na ndakisa, tosalelaka primary, success, mpe dangerbafungola uta $theme-colorsmpo na ba liens, ba boutons, mpe ba états ya formulaire. Kozongisa ba valeurs ya ba clés oyo esengeli ko présenter ba problèmes te, mais kolongola yango ekoki kosala ba problèmes ya compilation ya Sass. Na ba instances oyo, ekosenga o modifier code Sass oyo esalelaka ba valeurs wana.

Misala oyo esalaka

Bootstrap esalelaka ba fonctions ya Sass ebele, kasi kaka sous-ensemble moko nde ekoki kosalelama na thème général. Totie misala misato mpo na kozwa motuya uta na bakarte ya langi:

@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);
}

Yango epesaka yo nzela ya kopona langi moko na karte ya Sass mingi lokola ndenge olingaki kosalela variable ya langi uta na v3.

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

Tozali mpe na fonction mosusu mpo na kozwa niveau moko boye ya couleur na $theme-colorscarte. Ba valeurs ya niveau négatif eko éclairer couleur, alors que ba niveaux ya likolo eko molili.

@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);
}

Na pratique, olingaki o benga fonction pe o passer na deux paramètres : kombo ya couleur à partir ya $theme-colors(par exemple, primaire ou danger) na niveau numérique.

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

Ba fonctions ya kobakisa ekokaki kobakisa na mikolo ekoya to Sass na yo moko personnalisé mpo na kosala ba fonctions ya niveau mpo na ba cartes ya Sass ya kobakisa, to kutu moko ya générique soki olingaki kozala verbose mingi.

Bokeseni ya langi

Moko ya mosala mosusu oyo tozali kokɔtisa na Bootstrap ezali mosala ya kokesana na langi, color-yiq. Esalelaka esika ya langi ya YIQ mpo na kozongisa na ndenge ya automatique langi ya bokeseni ya pole ( #fff) to ya molili ( #111) na kotalela langi ya base oyo emonisami. Fonction oyo ezali surtout utile pona ba mixins to ba boucles esika ozali ko générer ba classes ebele.

Na ndakisa, mpo na kobimisa ba swatches ya langi uta na $theme-colorskarte na biso:

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

Ekoki mpe kosalelama mpo na bamposa ya bokeseni oyo esalemaka mbala moko:

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

Okoki pe ko préciser couleur ya base na ba fonctions na biso ya carte ya couleur:

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

Ba options ya Sass

Personnaliser Bootstrap 4 na fichier na biso ya ba variables personnalisées intégrées mpe toggler facilement ba préférences CSS mondiales na ba $enable-*variables ya sika ya Sass. Bolongola valeur ya variable moko pe recompiler na npm run testndenge esengeli.

Okoki koluka mpe kosala ba variables oyo mpo na ba options mondiales ya ntina na scss/_variables.scssfichier ya Bootstrap.

Variable oyo ekoki kobongwana Mituya ya bato Ndimbola
$spacer 1rem(ya liboso), to motuya nyonso > 0 Ezali kolakisa motuya ya espacer par défaut mpo na kobimisa na ndenge ya programme ba utilitaires na biso ya espacer .
$enable-rounded true(par défaut) tofalse Ezali kopesa nzela na ba styles oyo esili kolimbolama liboso border-radiusna ba composants ndenge na ndenge.
$enable-shadows trueto false(na ndenge ya liboso) . Ezali kopesa nzela na ba styles oyo esili kolimbolama liboso box-shadowna ba composants ndenge na ndenge.
$enable-gradients trueto false(na ndenge ya liboso) . Ezali kopesa nzela na ba gradients oyo esili kolimbolama na nzela ya background-imageba styles na ba composants ndenge na ndenge.
$enable-transitions true(par défaut) tofalse transitionEzali kopesa nzela na s oyo esili kolimbolama liboso na biloko ndenge na ndenge.
$enable-prefers-reduced-motion-media-query true(par défaut) tofalse Ezali kopesa nzela na prefers-reduced-motionmotuna ya media , oyo ekitisaka ba animations/transitions mosusu na kotalela ba préférences ya navigateur/système d’exploitation ya basaleli.
$enable-hover-media-query trueto false(na ndenge ya liboso) . Esili kosalelama te
$enable-grid-classes true(par défaut) tofalse Ezali kopesa nzela na bokeli ya ba kelasi ya CSS mpo na système ya grille (ndakisa, .container, .row, .col-md-1, etc.).
$enable-caret true(par défaut) tofalse Ezali kopesa nzela na caret ya pseudo élément na .dropdown-toggle.
$enable-print-styles true(par défaut) tofalse Ezali kopesa nzela na ba styles mpo na ko optimiser impression.
$enable-validation-icons true(par défaut) tofalse Ezali kopesa nzela background-imagena bilembo na kati ya ba entrées textuelles mpe mwa ba formulaire personnalisé mpo na ba états ya validation.

Langi

Mingi ya ba composants mpe ba utilitaires ndenge na ndenge ya Bootstrap etongami na nzela ya série ya ba couleurs oyo e définir na carte ya Sass. Carte oyo ekoki kozala boucle likolo na Sass mpo na kobimisa noki série ya ba ensembles ya mibeko.

Ba couleurs nionso

Ba couleurs nionso oyo ezali na Bootstrap 4, ezali lokola ba variables ya Sass mpe carte ya Sass na scss/_variables.scssfichier. Yango ekopanzana na ba sorties ya mike mike oyo ekolanda mpo na kobakisa ba nuances ya kobakisa, mingi lokola palette ya gris oyo tozali déjà ko inclure.

Bleu
Indigo
Pourpre
Rose
Motane
Lilala
Jaune
Vert
Teal
Cyan oyo azali

Tala ndenge okoki kosalela oyo na Sass na yo:

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

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

Ba classes ya utilité ya couleur ezali pe pona ko setting colorpe background-color.

Na mikolo ekoya, tokozala na mokano ya kopesa ba cartes ya Sass mpe ba variables mpo na ba nuances ya couleur moko na moko ndenge tosalaki na ba couleurs ya gris oyo ezali awa na se.

Ba couleurs ya thème

Tosalelaka sous-ensemble ya ba couleurs nionso pona kosala palette ya couleur ya moke pona ko générer ba schemes ya couleur, oyo ezali pe lokola ba variables ya Sass pe carte ya Sass na scss/_variables.scssfichier ya Bootstraps.

Ya liboso
Ebongiseli ya mibale
Kolonga
Likama
Likebisi
Info
Pole
Molili

Ba gris

Ensemble expansif ya ba variables ya gris na carte Sass na scss/_variables.scsspona ba nuances constantes ya gris na kati ya projet na yo. Boyeba ete oyo ezali « grises cool », oyo elingi kozala na ton bleu subtil, na esika ya ba gris neutres.

100
200
300
400
500
600
700
800
900

Na kati scss/_variables.scssya , okokuta ba variables ya couleur ya Bootstrap na carte ya Sass. Tala ndakisa ya $colorskarte ya Sass:

$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;

Bakisa, longola, to bongisa ba valeurs na kati ya carte mpo na ko actualiser ndenge nini esalelamaka na ba composants misusu ebele. Malheureusement na moment oyo, composant nionso te e utiliser carte oyo ya Sass. Ba mises à jour oyo ekoya ekosala makasi mpo na kobongisa likambo oyo. Kino tango wana, sala plan ya kosalela ba ${color}variables na carte oyo ya Sass.

Ba composants

Mingi ya ba composants na ba utilitaires ya Bootstrap etongami na @eachba boucles oyo ezo iterate likolo ya carte ya Sass. Yango ezali surtout utile pona ko générer ba variantes ya composante moko par notre $theme-colorspe ko créer ba variantes responsives pona point de rupture moko na moko. Lokola ozali ko personnaliser ba cartes oyo ya Sass mpe ko recompiler, okomona automatiquement ba changements na yo ezo refleter na ba boucles oyo.

Ba modificateurs

Mingi ya ba composants ya Bootstrap etongami na approche ya classe base-modifier. Yango elingi koloba ete eteni monene ya lolenge ya kosala ezali na kelasi ya moboko (ndakisa, .btn) nzokande mbongwana ya lolenge ekangami na kelasi ya mobongisi (ndakisa, .btn-danger). Ba classes ya modificateur oyo etongami à partir ya$theme-colors carte pona kosala personnalisation ya nombre na kombo ya ba classes na biso ya modificateur.

Tala ba exemples mibale ya ndenge to boucle likolo ya $theme-colorscarte pona ko générer ba modificateurs na .alertcomposant na ba .bg-*utilitaires na biso nionso ya fond.

// 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);
}

Koyanola

Ba boucles oyo ya Sass ekangami kaka na ba cartes ya couleur te, pe. Okoki mpe kobimisa ba variations responsives ya ba composants to ba utilitaires na yo. Bozua par exemple ba utilitaires na biso ya alignment ya texte responsif esika tosangisaka @eachboucle pona $grid-breakpointscarte Sass na requête ya media inclure.

@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; }
  }
}

Soki osengeli kobongola $grid-breakpoints, mbongwana na yo ekosalema na ba boucles nyonso oyo ezali kozongela likoló ya karte yango.

Ba variables ya CSS

Bootstrap 4 ezali na pene na douzaine mibale ya ba propriétés personnalisées ya CSS (variables) na CSS na yango oyo esangisi. Yango epesaka nzela ya pete na ba valeurs oyo esalelamaka mingi lokola ba couleurs ya thème na biso, ba points de rupture, mpe ba stacks ya ba fonts ya liboso tango ozali kosala na Inspecteur ya navigateur na yo, sandbox ya code, to prototyping général.

Ba variables oyo ezali

Tala ba variables oyo tozali ko kotisa (notez que the :rootezali requis). Bazali na kati ya _root.scssdossier na biso.

: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;
}

Bandakisa

Ba variables ya CSS epesaka flexibilité ya ndenge moko na ba variables ya Sass, kasi sans besoin ya compilation avant ya ko servir na navigateur. Par exemple, awa tozali ko réinitialiser ba styles ya fonte na lien ya page na biso na ba variables CSS.

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

Ba variables ya point de rupture

Atako totia na ebandeli ba points de rupture na ba variables na biso ya CSS (ndakisa, --breakpoint-md), oyo esungami te na ba requêtes ya media , kasi ekoki kaka kosalelama na kati ya ba ensembles ya mibeko na ba requêtes ya media. Ba variables oyo ya point de rupture etikali na CSS compilé pona compatibilité en arrière donné que ekoki ko utiliser na JavaScript. Yekola makambo mingi na spec .

Tala ndakisa ya oyo esungami te:

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

Mpe talá ndakisa ya makambo oyo esungami:

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