Как изменить размер кнопки bootstrap

Bootstrap 5 - быстрое создание и настройка адаптивных сайтов. Используйте настраиваемые стили кнопок Bootstrap для взаимодействия с формами, диалоговыми окнами, т.п. Имеется поддержка нескольких размеров, состояний и т.д. (Версия v5.0.2)

Примеры

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

<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>

<button type="button" class="btn btn-link">Link</button>
Использование вспомогательных технологий

Использование цвета как дополнительного инструмента информативности доступно только в визуальной сфере, что ограничивает пользователей вспомогательных технологий, например, программ для чтения текста с экрана. Удостоверьтесь, что информация обозначенная цветом, также доступна и из самого контента (например, видимый текст) или содержится в альтернативных средствах – таких как дополнительный скрытый в классе .visually-hidden текст.

Отключение переноса текста

Если вы не хотите переносить текст кнопки, вы можете добавить к ней класс .text-nowrap. В Sass вы можете установить $btn-white-space: nowrap чтобы отключить перенос текста для каждой кнопки.

Классы .btn созданы для использования с элементом <button>. Однако их также можно использовать внутри <a> или <input> (хотя из-за этого некоторые браузеры могут рендерить это немного иначе).

При использовании классов .btn в элементах <a>, которые в данном случае используются не как линк, ведущий на новые страницы или как якорь, а как триггер внутристраничной функциональности (такой как сворачивание содержимого), необходимо задать этим <a> атрибут role="button" для правильного поведения в случае применения вспомогательных технологий таких как «экранная читалка».

<a class="btn btn-primary" href="#" role="button">Link</a>
<button class="btn btn-primary" type="submit">Button</button>
<input class="btn btn-primary" type="button" value="Input">
<input class="btn btn-primary" type="submit" value="Submit">
<input class="btn btn-primary" type="reset" value="Reset">

Контурные кнопки (без фона)

Нужна кнопка, но без «тяжелых» фоновых цветов? Замените дефолтные классы-модификаторы на классы .btn-outline-* для удаления всех фоновых изображений и цветов в любой кнопке.

<button type="button" class="btn btn-outline-primary">Primary</button>
<button type="button" class="btn btn-outline-secondary">Secondary</button>
<button type="button" class="btn btn-outline-success">Success</button>
<button type="button" class="btn btn-outline-danger">Danger</button>
<button type="button" class="btn btn-outline-warning">Warning</button>
<button type="button" class="btn btn-outline-info">Info</button>
<button type="button" class="btn btn-outline-light">Light</button>
<button type="button" class="btn btn-outline-dark">Dark</button>

В некоторых стилях кнопок используется относительно светлый цвет переднего плана. И для того, чтобы обеспечить достаточный контраст их следует использовать только на темном фоне.

Размеры

Нужно изменить размеры кнопки? Добавьте в нее классы .btn-lg или .btn-sm для получения дополнительных размеров.

<button type="button" class="btn btn-primary btn-lg">Large button</button>
<button type="button" class="btn btn-secondary btn-lg">Large button</button>
<button type="button" class="btn btn-primary btn-sm">Small button</button>
<button type="button" class="btn btn-secondary btn-sm">Small button</button>

«Отключенние» кнопки

Заставьте кнопки выглядеть «неактивными» добавлением булеанова атрибута disabled к любому элементу <button>. Отключенные кнопки имеют значение pointer-events: none, что предотвращает срабатывание состояния наведения и активного состояния.

<button type="button" class="btn btn-lg btn-primary" disabled>Primary button</button>
<button type="button" class="btn btn-secondary btn-lg" disabled>Button</button>

«Отключенные» кнопки, созданные из элемента <a>, ведут себя немного иначе:

  • Элемент <a> не поддерживает атрибут disabled, так что для соответствующих свойств вместо него надо добавлять класс .disabled;
  • Некоторые future-friendly стили, которые поддерживаются не всеми юзер-агентами, (т.е. «возможно будут поддерживаться в будущем») включены в <a> для отключения всех событий pointer-events на кнопках-якорях. В браузерах, которые поддерживают это свойство, вы вовсе не увидите деактивированный курсор.
  • Отключенные кнопки должны содержать атрибут aria-disabled="true" для указания вспомогательным технологиям состояния элемента.
<a href="#" class="btn btn-primary btn-lg disabled" tabindex="-1" role="button" aria-disabled="true">Primary link</a>
<a href="#" class="btn btn-secondary btn-lg disabled" tabindex="-1" role="button" aria-disabled="true">Link</a>
Предупреждение о функциональности ссылок

Класс .disabled использует события-указатели pointer-events: none, чтобы попытаться отключить функциональность ссылок для <a>, но это свойство CSS еще не полностью стандартизировано. Кроме того, даже в браузерах, которые поддерживают свойство события-указателя pointer-events: none, при навигации с клавиатуры пользователи клавиатур для слабовидящих и иных вспомогательных технологий могут нечаянно пройти по данной ссылке. Так что для полной «безопасности», в дополнение к aria-disabled="true" добавьте в эти ссылки атрибут tabindex="-1" для предотвращения возможности «нахождения» их с клавиатуры, и используйте собственный JavaScript, чтобы полностью отключить их функциональность.

Блочные кнопки

Создавайте гибкие стопки полноразмерных «кнопок блока», как в Bootstrap 4, с помощью наших утилит display и разрывов. Используя утилиты вместо классов, специфичных для кнопок, мы получаем гораздо больший контроль над интервалами, выравниванием и адаптивным поведением.

<div class="d-grid gap-2">
  <button class="btn btn-primary" type="button">Button</button>
  <button class="btn btn-primary" type="button">Button</button>
</div>

Здесь мы создаем адаптивный вариант, начиная с вертикально расположенных кнопок до точки останова md, где .d-md-block заменяет класс .d-grid, тем самым сводя на нет параметры gap-2. Измените размер окна браузера, чтобы увидеть изменения.

<div class="d-grid gap-2 d-md-block">
  <button class="btn btn-primary" type="button">Button</button>
  <button class="btn btn-primary" type="button">Button</button>
</div>

Вы можете настроить ширину кнопок блока с помощью классов ширины столбцов сетки. Например, для «кнопки блока» половинной ширины используйте .col-6. Отцентрируйте его также по горизонтали с помощью .mx-auto.

<div class="d-grid gap-2 col-6 mx-auto">
  <button class="btn btn-primary" type="button">Button</button>
  <button class="btn btn-primary" type="button">Button</button>
</div>

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

<div class="d-grid gap-2 d-md-flex justify-content-md-end">
  <button class="btn btn-primary me-md-2" type="button">Button</button>
  <button class="btn btn-primary" type="button">Button</button>
</div>

Плагины кнопок

Контролируйте состояния кнопок или создавайте группы кнопок для компонентов, таких как «тулбары».

Визуально эти кнопки переключения идентичны кнопкам чекбоксам и радиокнопкам. Однако вспомогательные технологии передают их по-другому: переключатели чекбоксов будут объявлены программами чтения с экрана как «отмечено»/«не отмечено» (поскольку, несмотря на их внешний вид, они по сути остаются чекбоксами), тогда как эти переключатели будут объявлены как «Кнопка»/«кнопка нажата». Выбор между этими двумя подходами будет зависеть от типа создаваемого вами переключателя, а также от того, будет ли этот переключатель иметь смысл для пользователей, когда он будет объявлен как чекбокс или как фактическая кнопка.

Переключение состояний

Добавьте data-bs-toggle="button" для переключения на активное active состояние кнопки. Если вы предварительно переключаете кнопку, вам необходимо вручную добавить класс .active и aria-pressed="true" для гарантированой правильной передачи вспомогательным технологиям.

<button type="button" class="btn btn-primary" data-bs-toggle="button" autocomplete="off">Toggle button</button>
<button type="button" class="btn btn-primary active" data-bs-toggle="button" autocomplete="off" aria-pressed="true">Active toggle button</button>
<button type="button" class="btn btn-primary" disabled data-bs-toggle="button" autocomplete="off">Disabled toggle button</button>
<a href="#" class="btn btn-primary" role="button" data-bs-toggle="button">Toggle link</a>
<a href="#" class="btn btn-primary active" role="button" data-bs-toggle="button" aria-pressed="true">Active toggle link</a>
<a href="#" class="btn btn-primary disabled" tabindex="-1" aria-disabled="true" role="button" data-bs-toggle="button">Disabled toggle link</a>

Методы

Вы можете создать кнопки с помощью конструктора кнопки, например:

var button = document.getElementById('myButton')
var bsButton = new bootstrap.Button(button)
Метод Описание
toggle Переключает состояние нажатия. Придает кнопке вид, что она была активирована.
dispose Уничтожает элемент кнопку. (Удаляет сохраненные данные в элементе DOM)

Например, чтобы переключить все кнопки

var buttons = document.querySelectorAll('.btn')
buttons.forEach(function (button) {
  var button = new bootstrap.Button(button)
  button.toggle()
})

Sass

Переменные

$btn-padding-y:               $input-btn-padding-y;
$btn-padding-x:               $input-btn-padding-x;
$btn-font-family:             $input-btn-font-family;
$btn-font-size:               $input-btn-font-size;
$btn-line-height:             $input-btn-line-height;
$btn-white-space:             null; // Set to `nowrap` to prevent text wrapping

$btn-padding-y-sm:            $input-btn-padding-y-sm;
$btn-padding-x-sm:            $input-btn-padding-x-sm;
$btn-font-size-sm:            $input-btn-font-size-sm;

$btn-padding-y-lg:            $input-btn-padding-y-lg;
$btn-padding-x-lg:            $input-btn-padding-x-lg;
$btn-font-size-lg:            $input-btn-font-size-lg;

$btn-border-width:            $input-btn-border-width;

$btn-font-weight:             $font-weight-normal;
$btn-box-shadow:              inset 0 1px 0 rgba($white, .15), 0 1px 1px rgba($black, .075);
$btn-focus-width:             $input-btn-focus-width;
$btn-focus-box-shadow:        $input-btn-focus-box-shadow;
$btn-disabled-opacity:        .65;
$btn-active-box-shadow:       inset 0 3px 5px rgba($black, .125);

$btn-link-color:              $link-color;
$btn-link-hover-color:        $link-hover-color;
$btn-link-disabled-color:     $gray-600;

// Allows for customizing button radius independently from global border radius
$btn-border-radius:           $border-radius;
$btn-border-radius-sm:        $border-radius-sm;
$btn-border-radius-lg:        $border-radius-lg;

$btn-transition:              color .15s ease-in-out, background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out;

$btn-hover-bg-shade-amount:       15%;
$btn-hover-bg-tint-amount:        15%;
$btn-hover-border-shade-amount:   20%;
$btn-hover-border-tint-amount:    10%;
$btn-active-bg-shade-amount:      20%;
$btn-active-bg-tint-amount:       20%;
$btn-active-border-shade-amount:  25%;
$btn-active-border-tint-amount:   10%;

Миксины

Есть три миксина для кнопок: миксины для кнопок и вариантов контура кнопки (оба основаны на $theme-colors), плюс миксин размера кнопки.

@mixin button-variant(
  $background,
  $border,
  $color: color-contrast($background),
  $hover-background: if($color == $color-contrast-light, shade-color($background, $btn-hover-bg-shade-amount), tint-color($background, $btn-hover-bg-tint-amount)),
  $hover-border: if($color == $color-contrast-light, shade-color($border, $btn-hover-border-shade-amount), tint-color($border, $btn-hover-border-tint-amount)),
  $hover-color: color-contrast($hover-background),
  $active-background: if($color == $color-contrast-light, shade-color($background, $btn-active-bg-shade-amount), tint-color($background, $btn-active-bg-tint-amount)),
  $active-border: if($color == $color-contrast-light, shade-color($border, $btn-active-border-shade-amount), tint-color($border, $btn-active-border-tint-amount)),
  $active-color: color-contrast($active-background),
  $disabled-background: $background,
  $disabled-border: $border,
  $disabled-color: color-contrast($disabled-background)
) {
  color: $color;
  @include gradient-bg($background);
  border-color: $border;
  @include box-shadow($btn-box-shadow);

  &:hover {
    color: $hover-color;
    @include gradient-bg($hover-background);
    border-color: $hover-border;
  }

  .btn-check:focus + &,
  &:focus {
    color: $hover-color;
    @include gradient-bg($hover-background);
    border-color: $hover-border;
    @if $enable-shadows {
      @include box-shadow($btn-box-shadow, 0 0 0 $btn-focus-width rgba(mix($color, $border, 15%), .5));
    } @else {
      // Avoid using mixin so we can pass custom focus shadow properly
      box-shadow: 0 0 0 $btn-focus-width rgba(mix($color, $border, 15%), .5);
    }
  }

  .btn-check:checked + &,
  .btn-check:active + &,
  &:active,
  &.active,
  .show > &.dropdown-toggle {
    color: $active-color;
    background-color: $active-background;
    // Remove CSS gradients if they're enabled
    background-image: if($enable-gradients, none, null);
    border-color: $active-border;

    &:focus {
      @if $enable-shadows {
        @include box-shadow($btn-active-box-shadow, 0 0 0 $btn-focus-width rgba(mix($color, $border, 15%), .5));
      } @else {
        // Avoid using mixin so we can pass custom focus shadow properly
        box-shadow: 0 0 0 $btn-focus-width rgba(mix($color, $border, 15%), .5);
      }
    }
  }

  &:disabled,
  &.disabled {
    color: $disabled-color;
    background-color: $disabled-background;
    // Remove CSS gradients if they're enabled
    background-image: if($enable-gradients, none, null);
    border-color: $disabled-border;
  }
}
@mixin button-outline-variant(
  $color,
  $color-hover: color-contrast($color),
  $active-background: $color,
  $active-border: $color,
  $active-color: color-contrast($active-background)
) {
  color: $color;
  border-color: $color;

  &:hover {
    color: $color-hover;
    background-color: $active-background;
    border-color: $active-border;
  }

  .btn-check:focus + &,
  &:focus {
    box-shadow: 0 0 0 $btn-focus-width rgba($color, .5);
  }

  .btn-check:checked + &,
  .btn-check:active + &,
  &:active,
  &.active,
  &.dropdown-toggle.show {
    color: $active-color;
    background-color: $active-background;
    border-color: $active-border;

    &:focus {
      @if $enable-shadows {
        @include box-shadow($btn-active-box-shadow, 0 0 0 $btn-focus-width rgba($color, .5));
      } @else {
        // Avoid using mixin so we can pass custom focus shadow properly
        box-shadow: 0 0 0 $btn-focus-width rgba($color, .5);
      }
    }
  }

  &:disabled,
  &.disabled {
    color: $color;
    background-color: transparent;
  }
}
@mixin button-size($padding-y, $padding-x, $font-size, $border-radius) {
  padding: $padding-y $padding-x;
  @include font-size($font-size);
  // Manually declare to provide an override to the browser default
  @include border-radius($border-radius, 0);
}

Циклы

Варианты кнопок (для обычных и контурных кнопок) используют соответствующие миксины с нашей картой $theme-colors для генерации классов модификаторов в scss/_buttons.scss.

@each $color, $value in $theme-colors {
  .btn-#{$color} {
    @include button-variant($value, $value);
  }
}

@each $color, $value in $theme-colors {
  .btn-outline-#{$color} {
    @include button-outline-variant($value);
  }
}

Пример кнопки с иконкой

Используйте Bootstrap иконки.

<button type="button" class="btn btn-primary">
<i class="bi bi-cloud-upload-fill"></i> Кнопка с иконкой
</button>

Use Bootstrap’s custom button styles for actions in forms, dialogs, and more with support for multiple sizes, states, and more.

Examples

Bootstrap includes several predefined button styles, each serving its own semantic purpose, with a few extras thrown in for more control.

<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>

<button type="button" class="btn btn-link">Link</button>
Conveying meaning to assistive technologies

Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (e.g. the visible text), or is included through alternative means, such as additional text hidden with the .sr-only class.

The .btn classes are designed to be used with the <button> element. However, you can also use these classes on <a> or <input> elements (though some browsers may apply a slightly different rendering).

When using button classes on <a> elements that are used to trigger in-page functionality (like collapsing content), rather than linking to new pages or sections within the current page, these links should be given a role="button" to appropriately convey their purpose to assistive technologies such as screen readers.

<a class="btn btn-primary" href="#" role="button">Link</a>
<button class="btn btn-primary" type="submit">Button</button>
<input class="btn btn-primary" type="button" value="Input">
<input class="btn btn-primary" type="submit" value="Submit">
<input class="btn btn-primary" type="reset" value="Reset">

Outline buttons

In need of a button, but not the hefty background colors they bring? Replace the default modifier classes with the .btn-outline-* ones to remove all background images and colors on any button.

<button type="button" class="btn btn-outline-primary">Primary</button>
<button type="button" class="btn btn-outline-secondary">Secondary</button>
<button type="button" class="btn btn-outline-success">Success</button>
<button type="button" class="btn btn-outline-danger">Danger</button>
<button type="button" class="btn btn-outline-warning">Warning</button>
<button type="button" class="btn btn-outline-info">Info</button>
<button type="button" class="btn btn-outline-light">Light</button>
<button type="button" class="btn btn-outline-dark">Dark</button>

Sizes

Fancy larger or smaller buttons? Add .btn-lg or .btn-sm for additional sizes.

<button type="button" class="btn btn-primary btn-lg">Large button</button>
<button type="button" class="btn btn-secondary btn-lg">Large button</button>
<button type="button" class="btn btn-primary btn-sm">Small button</button>
<button type="button" class="btn btn-secondary btn-sm">Small button</button>

Create block level buttons—those that span the full width of a parent—by adding .btn-block.

<button type="button" class="btn btn-primary btn-lg btn-block">Block level button</button>
<button type="button" class="btn btn-secondary btn-lg btn-block">Block level button</button>

Active state

Buttons will appear pressed (with a darker background, darker border, and inset shadow) when active. There’s no need to add a class to <button>s as they use a pseudo-class. However, you can still force the same active appearance with .active (and include the aria-pressed="true" attribute) should you need to replicate the state programmatically.

<a href="#" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Primary link</a>
<a href="#" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Link</a>

Disabled state

Make buttons look inactive by adding the disabled boolean attribute to any <button> element.

<button type="button" class="btn btn-lg btn-primary" disabled>Primary button</button>
<button type="button" class="btn btn-secondary btn-lg" disabled>Button</button>

Disabled buttons using the <a> element behave a bit different:

  • <a>s don’t support the disabled attribute, so you must add the .disabled class to make it visually appear disabled.
  • Some future-friendly styles are included to disable all pointer-events on anchor buttons. In browsers which support that property, you won’t see the disabled cursor at all.
  • Disabled buttons should include the aria-disabled="true" attribute to indicate the state of the element to assistive technologies.
<a href="#" class="btn btn-primary btn-lg disabled" role="button" aria-disabled="true">Primary link</a>
<a href="#" class="btn btn-secondary btn-lg disabled" role="button" aria-disabled="true">Link</a>
Link functionality caveat

The .disabled class uses pointer-events: none to try to disable the link functionality of <a>s, but that CSS property is not yet standardized. In addition, even in browsers that do support pointer-events: none, keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, add a tabindex="-1" attribute on these links (to prevent them from receiving keyboard focus) and use custom JavaScript to disable their functionality.

Button plugin

Do more with buttons. Control button states or create groups of buttons for more components like toolbars.

Toggle states

Add data-toggle="button" to toggle a button’s active state. If you’re pre-toggling a button, you must manually add the .active class and aria-pressed="true" to the <button>.

<button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
  Single toggle
</button>

Checkbox and radio buttons

Bootstrap’s .button styles can be applied to other elements, such as <label>s, to provide checkbox or radio style button toggling. Add data-toggle="buttons" to a .btn-group containing those modified buttons to enable their toggling behavior via JavaScript and add .btn-group-toggle to style the <input>s within your buttons. Note that you can create single input-powered buttons or groups of them.

The checked state for these buttons is only updated via click event on the button. If you use another method to update the input—e.g., with <input type="reset"> or by manually applying the input’s checked property—you’ll need to toggle .active on the <label> manually.

Note that pre-checked buttons require you to manually add the .active class to the input’s <label>.

<div class="btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-secondary active">
    <input type="checkbox" checked autocomplete="off"> Checked
  </label>
</div>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-secondary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Active
  </label>
  <label class="btn btn-secondary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio
  </label>
  <label class="btn btn-secondary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio
  </label>
</div>

Methods

Method Description
$().button('toggle') Toggles push state. Gives the button the appearance that it has been activated.
$().button('dispose') Destroys an element’s button.

Примеры

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

<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>

<button type="button" class="btn btn-link">Link</button>
Передача смысла вспомогательным технологиям

Использование цвета для добавления смысла обеспечивает только визуальную индикацию, которая не будет передана пользователям вспомогательных технологий, таких как программы чтения с экрана. Убедитесь, что Info, обозначенная цветом, либо очевидна из самого содержимого (например, видимый текст), либо включена с помощью альтернативных средств, таких как дополнительный текст, скрытый с .sr-only классом.

Отключить перенос текста

Если вы не хотите, чтобы текст кнопки переносился, вы можете добавить .text-nowrapкласс к кнопке. В Sass вы можете $btn-white-space: nowrapотключить перенос текста для каждой кнопки.

Эти .btnклассы предназначены для использования с элементом <button>. Однако вы также можете использовать эти классы в элементах <a> или <input> (хотя некоторые браузеры могут применять немного другой рендеринг).

При использовании классов кнопок в <a> элементах, которые используются для запуска функциональности на странице (например, сворачивания содержимого), вместо того, чтобы ссылаться на новые страницы или разделы на текущей странице, этим Linkм следует присвоить role="button", чтобы соответствующим образом передать их назначение вспомогательным технологиям, таким как программы чтения с экрана.

<a class="btn btn-primary" href="#" role="button">Link</a>
<button class="btn btn-primary" type="submit">Кнопка</button>
<input class="btn btn-primary" type="button" value="Input">
<input class="btn btn-primary" type="submit" value="Отправить">
<input class="btn btn-primary" type="reset" value="Reset">

Контур кнопки

Нужна кнопка, но не богатые цвета фона, которые они приносят? Замените классы модификаторов по умолчанию на .btn-outline-*те, чтобы удалить все фоновые изображения и цвета на любой кнопке.

<button type="button" class="btn btn-outline-primary">Primary</button>
<button type="button" class="btn btn-outline-secondary">Secondary</button>
<button type="button" class="btn btn-outline-success">Success</button>
<button type="button" class="btn btn-outline-danger">Danger</button>
<button type="button" class="btn btn-outline-warning">Warning</button>
<button type="button" class="btn btn-outline-info">Info</button>
<button type="button" class="btn btn-outline-light">Light</button>
<button type="button" class="btn btn-outline-dark">Dark</button>

Размеры

Хотите кнопки большего или меньшего размера? Добавьте .btn-lg или .btn-sm для изменения размеров.

<button type="button" class="btn btn-primary btn-lg">Большая кнопка</button>
<button type="button" class="btn btn-secondary btn-lg">Большая кнопка</button>
<button type="button" class="btn btn-primary btn-sm">Маленькая кнопка</button>
<button type="button" class="btn btn-secondary btn-sm">Маленькая кнопка</button>

Создайте кнопки уровня блока — те, которые охватывают всю ширину родительского элемента — путем добавления .btn-block.

<button type="button" class="btn btn-primary btn-lg btn-block">Block level button</button>
<button type="button" class="btn btn-secondary btn-lg btn-block">Block level button</button>

Отключенное состояние

Сделайте кнопки неактивными, добавив логический атрибут disabled к любому <button> элементу. Отключенные кнопки pointer-events: none применяются к, предотвращая срабатывание состояния наведения и активного состояния.

<button type="button" class="btn btn-lg btn-primary" disabled>Primary button</button>
<button type="button" class="btn btn-secondary btn-lg" disabled>Button</button>

Отключенные кнопки, использующие <a> элемент, ведут себя немного иначе:

  • <a> не поддерживают disabled атрибут, поэтому вы должны добавить .disabled класс, чтобы он визуально казался отключенным.
  • Включены некоторые удобные для будущего стили, чтобы отключить все pointer-events кнопки привязки. В браузерах, которые поддерживают это свойство, вы вообще не увидите отключенный курсор.
  • Отключенные кнопки должны включать aria-disabled="true" атрибут, указывающий состояние элемента для вспомогательных технологий.
<a href="#" class="btn btn-primary btn-lg disabled" tabindex="-1" role="button" aria-disabled="true">Primary link</a>
<a href="#" class="btn btn-secondary btn-lg disabled" tabindex="-1" role="button" aria-disabled="true">Link</a>
Warning о функциональности ссылок

.disabledКласс использует , pointer-events: noneчтобы попытаться отключить функциональность линии связи <a>с, но это свойство CSS еще не стандартизированы. Кроме того, даже в поддерживаемых браузерах pointer-events: noneнавигация с помощью клавиатуры остается неизменной, а это означает, что зрячие пользователи клавиатуры и пользователи вспомогательных технологий по-прежнему смогут активировать эти ссылки. Чтобы быть в безопасности, добавьте tabindex="-1"атрибут к этим Linkм (чтобы они не получали фокус клавиатуры) и используйте собственный JavaScript, чтобы отключить их функциональность.

Плагин кнопки

Плагин кнопок позволяет создавать простые кнопки включения / выключения.

Переключить состояния

Добавить, data-toggle="button" чтобы переключить состояние кнопки active. Если вы предварительно переключаете кнопку, вы должны вручную добавить .active класс и aria-pressed="true" в <button>.

<button type="button" class="btn btn-primary" data-toggle="button" autocomplete="off">Toggle button</button>
<button type="button" class="btn btn-primary active" data-toggle="button" autocomplete="off" aria-pressed="true">Active toggle button</button>
<button type="button" class="btn btn-primary" disabled data-toggle="button" autocomplete="off">Disabled toggle button</button>
<a href="#" class="btn btn-primary" role="button" data-toggle="button">Toggle link</a>
<a href="#" class="btn btn-primary active" role="button" data-toggle="button" aria-pressed="true">Active toggle link</a>
<a href="#" class="btn btn-primary disabled" role="button" data-toggle="button">Disabled toggle link</a>

Методы

Вы можете создать экземпляр кнопки с помощью конструктора кнопки, например:

var button = document.getElementById('myButton')
var bsButton = new bootstrap.Button(button)
Метод Описание
toggle Переключает состояние push. Придает кнопке вид, что она была активирована.
dispose Уничтожает кнопку элемента.

Например, чтобы переключить все кнопки

var buttons = document.querySelectorAll('.btn')
buttons.forEach(function (button) {
  var button = new bootstrap.Button(button)
  button.toggle()
})

Buttons are one of the most popular and searched Bootstrap components. They offer many options, forms and
functionalities and in this lesson we will explore some of them.

First, let’s look at the button from our Call to Action.

Learn with me

Basics

We have 2 classes here.

The first btn class is the so-called base class. It defines the basic properties of
the button and is present in every button, regardless of its type. Remember to always include it.

The second btn-primary class is the so-called modifier class. It defines a specific
appearance for a given button. In this case -primary means the characteristic blue color which is the main design color of the MDB
system.

Note that we’re using the <a> element here. The .btn classes are designed to be used with the
<button> element. However, you can also use these classes on
<a> if you want to use them as a links. Just remember to add an additional role="button" attribute to them.

Colors

You can easily change the button color by changing the modifier class.

Contextual

For example, MDB includes several predefined button styles, each serving its own semantic purpose.

Neutral

Neutral buttons provide additional light and dark colors.

Link

Link button is similar to the tertiary button mentioned below (and often is used as a substitute). The difference
is, that the link button has a background on hover and also has a default padding.

Hierarchy

Buttons, as one of the key UI elements, must have their own hierarchy. This means that the user should be able to
easily identify which button is the most important (primary button), which is less important (secondary button) and
which presents completely additional information (tertiary button).

Elements with strong, filled backgrounds and shadows attract attention the most, which is why button
primary
is built in this way.

A delicate background without shadows is less engaging, so it is well suited for button secondary.

The lack of background and shadow makes the element the least visible. These features characterize the
button tertiary.

Note: Button tertiary may require additional margins. Without extra margins, the button edge will
be flush with adjacent elements (which is sometimes the desired result). If you need margin — simply add margin utility classes like mx-2.

Outline

In need of a button, but not the hefty background colors they bring? Replace the default
modifier classes with the .btn-outline-* ones to remove all background images and
colors on any button.

Rounded

Add .btn-rounded class to make the button rounded.

Sizes

Fancy larger or smaller buttons? Add .btn-lg or .btn-sm for
additional sizes.

Floating

Use .btn-floating class to make a circle button.

To make it works properly you have to put an icon inside. The text will not
fit in. You can find hundreds of available icons in our
icons docs.

Ripple

I suspect you’ve noticed that cute wave effect when you click the button.

This is the so-called «ripple effect», characteristic of Material Design. It is automatically added to each button. By default, it has a white color however, we can manipulate it.

For example, if you want to change the color of a ripple, you can do so by adding the data-mdb-ripple-color attribute to the button and then defining the color.

Now it’s red.

Note: Ripple has many options and we will learn about them in future lessons. However, if you want to experiment with it now, check out the ripple documentation page.


Okay, let’s go back to our project now. I would like a button in our Call to Action:

  1. Had a slightly lighter color (btn-secondary class should do the trick)
  2. Was rounded (we’ll use the btn-rounded class)
  3. Had ripple effect in primary color (we will use data-mdb-ripple-color attribute)
  4. Had an icon (we’ll use a nice student hat icon, from the MDB icon collection )

Modify the button code in your project as follows:

Alright, it looks good! If you want to learn more about buttons have a look at the buttons documentation page.

Now let’s move to the next lesson.




John Doe

About author

Michal Szymanski

Co Founder at MDBootstrap / Listed in Forbes „30 under 30″ /
Open-source enthusiast / Dancer, nerd &
book lover.

Author of hundreds of articles on programming, business, marketing and productivity. In the past, an educator
working with troubled youth in orphanages and correctional facilities.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер кластера на флешке fat32
  • Как изменить размер кластера ext4
  • Как изменить размер клавиш на телефоне хонор
  • Как изменить размер клавиш на клавиатуре андроид
  • Как изменить размер клавиш на swiftkey

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии