Bootstrap classes in html

Components

Learn how and why we build nearly all our components responsively and with base and modifier classes.

Base classes

Bootstrap’s components are largely built with a base-modifier nomenclature. We group as many shared properties as possible into a base class, like .btn , and then group individual styles for each variant into modifier classes, like .btn-primary or .btn-success .

To build our modifier classes, we use Sass’s @each loops to 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.

Check out our Sass maps and loops docs for how to customize these loops and extend Bootstrap’s base-modifier approach to your own code.

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 and .list-group components.

// Generate contextual modifier classes for colorizing the alert  @each $state in map-keys($theme-colors)   .alert-#$state>   --#alert-color: var(--#$prefix>#$state>-text-emphasis);  --#alert-bg: var(--#$prefix>#$state>-bg-subtle);  --#alert-border-color: var(--#$prefix>#$state>-border-subtle);  --#alert-link-color: var(--#$prefix>#$state>-text-emphasis);  > > 
// List group contextual variants // // Add modifier classes to change text and background color on individual items. // Organizationally, this must come after the `:hover` states.  @each $state in map-keys($theme-colors)   .list-group-item-#$state>   --#list-group-color: var(--#$prefix>#$state>-text-emphasis);  --#list-group-bg: var(--#$prefix>#$state>-bg-subtle);  --#list-group-border-color: var(--#$prefix>#$state>-border-subtle);  --#list-group-action-hover-color: var(--#$prefix>emphasis-color);  --#list-group-action-hover-bg: var(--#$prefix>#$state>-border-subtle);  --#list-group-action-active-color: var(--#$prefix>emphasis-color);  --#list-group-action-active-bg: var(--#$prefix>#$state>-border-subtle);  --#list-group-active-color: var(--#$prefix>#$state>-bg-subtle);  --#list-group-active-bg: var(--#$prefix>#$state>-text-emphasis);  --#list-group-active-border-color: var(--#$prefix>#$state>-text-emphasis);  > > 

Responsive

These Sass loops aren’t limited to color maps, either. You can also generate responsive variations of your components. Take for example our responsive alignment of the dropdowns where we mix an @each loop for the $grid-breakpoints Sass map with a media query include.

// We deliberately hardcode the `bs-` prefix because we check // this custom property in JS to determine Popper's positioning  @each $breakpoint in map-keys($grid-breakpoints)   @include media-breakpoint-up($breakpoint)   $infix: breakpoint-infix($breakpoint, $grid-breakpoints);   .dropdown-menu#$infix>-start   --bs-position: start;   &[data-bs-popper]   right: auto;  left: 0;  >  >   .dropdown-menu#$infix>-end   --bs-position: end;   &[data-bs-popper]   right: 0;  left: auto;  >  >  > > 

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

$grid-breakpoints: (  xs: 0,  sm: 576px,  md: 768px,  lg: 992px,  xl: 1200px,  xxl: 1400px ); 

For more information and examples on how to modify our Sass maps and variables, please refer to the CSS section of the Grid documentation.

Creating your own

We encourage you to adopt these guidelines when building with Bootstrap to create your own components. We’ve extended this approach ourselves to the custom components in our documentation and examples. Components like our callouts are built just like our provided components with base and modifier classes.

This is a callout. We built it custom for our docs so our messages to you stand out. It has three variants via modifier classes.

In your CSS, you’d have something like the following where the bulk of the styling is done via .callout . Then, the unique styles between each variant is controlled via modifier class.

// Base class  .callout <>  // Modifier classes  .callout-info <> .callout-warning <> .callout-danger <> 

For the callouts, that unique styling is just a border-left-color . When you combine that base class with one of those modifier classes, you get your complete component family:

Источник

Компоненты

Узнайте, как и почему мы создаем почти все наши компоненты адаптивно, используя базовые классы и классы-модификаторы.

Базовые классы

Компоненты Bootstrap в основном построены с использованием номенклатуры базовых модификаторов. Мы группируем как можно больше общих свойств в базовый класс, например .btn , а затем группируем отдельные стили для каждого варианта в классы-модификаторы, такие как .btn-primary или .btn-success .

Чтобы создать наши классы-модификаторы, мы используем циклы Sass @each для итерации по карте Sass. Это особенно полезно для генерации вариантов компонента с помощью нашей $theme-colors и создания адаптивных вариантов для каждой контрольной точки. Когда Вы настраиваете эти карты Sass и перекомпилируете, Вы автоматически увидите свои изменения, отраженные в этих циклах.

Ознакомьтесь с нашей документацией по картам и циклам Sass, чтобы узнать, как настроить эти циклы и расширить подход Bootstrap с базовыми модификаторами к Вашему собственному коду.

Модификаторы

Многие компоненты Bootstrap построены с использованием подхода базового модификатора. Это означает, что основная часть стилей содержится в базовом классе (например, .btn ), в то время как варианты стилей ограничиваются классами-модификаторами (например, .btn-danger ). Эти классы модификаторов построены из карты $theme-colors для настройки количества и имени наших классов модификаторов.

Вот два примера того, как мы перебираем карту $theme-colors в цикле для генерации модификаторов для компонентов .alert и .list-group .

// Generate contextual modifier classes for colorizing the alert. @each $state, $value in $theme-colors  $alert-background: shift-color($value, $alert-bg-scale); $alert-border: shift-color($value, $alert-border-scale); $alert-color: shift-color($value, $alert-color-scale); @if (contrast-ratio($alert-background, $alert-color)  $min-contrast-ratio)  $alert-color: mix($value, color-contrast($alert-background), abs($alert-color-scale)); > .alert-#$state>  @include alert-variant($alert-background, $alert-border, $alert-color); > > 
// List group contextual variants // // Add modifier classes to change text and background color on individual items. // Organizationally, this must come after the `:hover` states. @each $state, $value in $theme-colors  $list-group-variant-bg: shift-color($value, $list-group-item-bg-scale); $list-group-variant-color: shift-color($value, $list-group-item-color-scale); @if (contrast-ratio($list-group-variant-bg, $list-group-variant-color)  $min-contrast-ratio)  $list-group-variant-color: mix($value, color-contrast($list-group-variant-bg), abs($list-group-item-color-scale)); > @include list-group-item-variant($state, $list-group-variant-bg, $list-group-variant-color); > 

Адаптивность

Эти циклы Sass также не ограничиваются цветовыми картами. Вы также можете создавать адаптивные варианты Ваших компонентов. Возьмем, к примеру, наше адаптивное выравнивание выпадающих списков, где мы смешиваем цикл @each для карты Sass $grid-breakpoints с включением медиа-запроса.

// We deliberately hardcode the `bs-` prefix because we check // this custom property in JS to determine Popper's positioning @each $breakpoint in map-keys($grid-breakpoints)  @include media-breakpoint-up($breakpoint)  $infix: breakpoint-infix($breakpoint, $grid-breakpoints); .dropdown-menu#$infix>-start  --bs-position: start; &[data-bs-popper]  right: auto; left: 0; > > .dropdown-menu#$infix>-end  --bs-position: end; &[data-bs-popper]  right: 0; left: auto; > > > > 

Если вы измените свои $grid-breakpoints , Ваши изменения будут применяться ко всем циклам, повторяющимся по этой карте.

$grid-breakpoints: ( xs: 0, sm: 576px, md: 768px, lg: 992px, xl: 1200px, xxl: 1400px ); 

Для получения дополнительной информации и примеров того, как изменить наши карты и переменные Sass, обратитесь к разделу Sass документации по Сетке.

Создание собственного

Мы рекомендуем Вам следовать этим рекомендациям при сборке с помощью Bootstrap, чтобы создавать свои собственные компоненты. Мы сами распространили этот подход на пользовательские компоненты в нашей документации и примерах. Компоненты, подобные нашим сноскам, создаются так же, как предоставленные нами компоненты с базовыми классами и модификаторами.

Это сноска. Мы создали его специально для наших документов, чтобы наши сообщения вам выделялись. Он имеет три варианта через классы модификаторов.

В Вашем CSS у Вас будет что-то вроде следующего, где основная часть стиля выполняется через .callout . Затем уникальные стили между каждым вариантом контролируются с помощью класса модификатора.

// Базовый класс .callout <> // Классы модификаторов .callout-info <> .callout-warning <> .callout-danger <> 

Для сноски этот уникальный стиль представляет собой просто border-left-color . Когда Вы объединяете этот базовый класс с одним из этих классов-модификаторов, Вы получаете полное семейство компонентов:

Источник

Читайте также:  32223 crimson keep introspurt html
Оцените статью