Bootstrap icons

Community

Stay up to date on the development of Bootstrap and reach out to the community with these helpful resources.

  • Read and subscribe to The Official Bootstrap Blog.
  • Join the official Slack room.
  • Chat with fellow Bootstrappers in IRC. On the server, in the channel.
  • Implementation help may be found at Stack Overflow (tagged ).
  • Developers should use the keyword on packages that modify or add to the functionality of Bootstrap when distributing through npm or similar delivery mechanisms for maximum discoverability.

You can also follow @getbootstrap on Twitter for the latest gossip and awesome music videos.

Печать

Даже в некоторых современных браузерах, для обеспечения печати приходится изловчиться.

В частности, в Chrome версии 32 независимо от параметров отступов и размеров полей, Chrome при печати использует значительно более узкую область просмотра, чем физический размер бумаги при отображении медиа запросов. Это может привести к тому, при печати Bootstrap неожиданно активирует очень мелкую сетку. и Ошибке Chrome #273306. Рекомендуемые обходные пути:

  • Примените extra-small разметку и убедитесь, что ваша страница выглядит приемлемо.
  • Настройка значения Less переменных, чтобы ваш бумага для принтера рассматривалась больше, чем extra-small.
  • Добавить Пользовательское медиа запросы изменение грид Размер точки останова для печати медиа только.

Также, как Сафари и v8.0, фиксированной ширины может вызвать Сафари использовать необычайно маленький размер шрифта при печати. См. #14868 и В WebKit ошибка #138192 Для более подробной информации. Одним из возможных обойти это, добавив следующие CSS:

Глобально важно

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

Тип текущего документа

Bootstrap требует использования doctype HTML5. Без него Вы увидите несколько забавных неполных стилей, но его включение не должно вызывать каких-либо серьезных сбоев.

Адаптивный метатег

Bootstrap разработан mobile first (сначала мобильный), стратегия, в которой мы сначала оптимизируем код для мобильных устройств, а затем масштабируем компоненты по мере необходимости с помощью медиа-запросов CSS. Чтобы обеспечить правильный рендеринг и сенсорное масштабирование для всех устройств, добавьте метатег адаптивного окна просмотра (viewport) к Вашему .

Вы можете увидеть пример этого в действии в .

Свойство Box-sizing

Для более простого изменения размеров в CSS мы переключаем глобальное значение с на . Это гарантирует, что не влияет на окончательную вычисленную ширину элемента, но может вызвать проблемы с некоторым сторонним программным обеспечением, таким как Google Maps и Google Custom Search Engine.

В редких случаях Вам нужно переопределить его, используйте что-то вроде следующего:

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

Узнайте больше о коробочной модели и размерах на сайте CSS Tricks.

Перезагрузка

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

Important globals

Bootstrap employs a handful of important global styles and settings that you’ll need to be aware of when using it, all of which are almost exclusively geared towards the normalization of cross browser styles. Let’s dive in.

HTML5 doctype

Bootstrap requires the use of the HTML5 doctype. Without it, you’ll see some funky incomplete styling, but including it shouldn’t cause any considerable hiccups.

Responsive meta tag

Bootstrap is developed mobile first, a strategy in which we optimize code for mobile devices first and then scale up components as necessary using CSS media queries. To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your .

You can see an example of this in action in the .

Box-sizing

For more straightforward sizing in CSS, we switch the global value from to . This ensures does not affect the final computed width of an element, but it can cause problems with some third party software like Google Maps and Google Custom Search Engine.

On the rare occasion you need to override it, use something like the following:

With the above snippet, nested elements—including generated content via and —will all inherit the specified for that .

Learn more about box model and sizing at CSS Tricks.

Reboot

For improved cross-browser rendering, we use Reboot to correct inconsistencies across browsers and devices while providing slightly more opinionated resets to common HTML elements.

Процентное округления в Safari

Движок для отображения версий Safari до версии v7.1 для OS X и Safari для iOS В8.0 были некоторые проблемы с количеством десятичных знаков, используемых в нашем грид классов. Так что если у вас 12 индивидуальный грид столбцы, Вы заметите, что они придумали короткие по сравнению с другими рядами колонн. Помимо обновления сафари на iOS, у вас есть несколько вариантов решений:

  • Добавить в вашей последней колонки в разметке, чтобы получить жесткое выравнивание по правому краю.
  • Изменить проценты вручную, чтобы получить идеальное округления для Safari (более сложно, чем в первом варианте)

What is Bootstrap?

  • Bootstrap is a free front-end framework for faster and easier web development
  • Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other, as well as optional JavaScript plugins
  • Bootstrap also gives you the ability to easily create responsive designs

What is Responsive Web Design?
Responsive web design is about creating web sites which automatically adjust
themselves to look good on all devices, from small phones to large desktops.

Bootstrap Example

<div class=»jumbotron text-center»>  <h1>My First Bootstrap Page</h1>  <p>Resize this responsive page to see the effect!</p> </div><div class=»container»>  <div class=»row»>
    <div class=»col-sm-4″>      <h3>Column 1</h3>      <p>Lorem ipsum
dolor..</p>    </div>    <div class=»col-sm-4″>      <h3>Column 2</h3>      <p>Lorem ipsum
dolor..</p>    </div>    <div class=»col-sm-4″>      <h3>Column 3</h3>       <p>Lorem ipsum
dolor..</p>    </div>  </div></div>

Responsive classes

Bootstrap’s grid includes six tiers of predefined classes for building complex responsive layouts. Customize the size of your columns on extra small, small, medium, large, or extra large devices however you see fit.

All breakpoints

For grids that are the same from the smallest of devices to the largest, use the and classes. Specify a numbered class when you need a particularly sized column; otherwise, feel free to stick to .

col
col
col
col

col-8
col-4

Stacked to horizontal

Using a single set of classes, you can create a basic grid system that starts out stacked and becomes horizontal at the small breakpoint ().

col-sm-8
col-sm-4

col-sm
col-sm
col-sm

Mix and match

Don’t want your columns to simply stack in some grid tiers? Use a combination of different classes for each tier as needed. See the example below for a better idea of how it all works.

.col-md-8
.col-6 .col-md-4

.col-6 .col-md-4
.col-6 .col-md-4
.col-6 .col-md-4

.col-6
.col-6

Row columns

Use the responsive classes to quickly set the number of columns that best render your content and layout. Whereas normal classes apply to the individual columns (e.g., ), the row columns classes are set on the parent as a default for contained columns. With you can give the columns their natural width.

Use these row columns classes to quickly create basic grid layouts or to control your card layouts and override when needed at the column level.

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column

Column
Column
Column
Column
Column
Column
Column
Column
Column
Column
Column
Column

You can also use the accompanying Sass mixin, :

Auto-layout columns

Utilize breakpoint-specific column classes for easy column sizing without an explicit numbered class like .

Equal-width

For example, here are two grid layouts that apply to every device and viewport, from to . Add any number of unit-less classes for each breakpoint you need and every column will be the same width.

1 of 2

2 of 2

1 of 3

2 of 3

3 of 3

Equal-width columns can be broken into multiple lines, but there was a that prevented this from working without an explicit or . There are workarounds for older browser versions, but they shouldn’t be necessary if you’re up-to-date.

Column
Column

Column
Column

Setting one column width

Auto-layout for flexbox grid columns also means you can set the width of one column and have the sibling columns automatically resize around it. You may use predefined grid classes (as shown below), grid mixins, or inline widths. Note that the other columns will resize no matter the width of the center column.

1 of 3

2 of 3 (wider)

3 of 3

1 of 3

2 of 3 (wider)

3 of 3

Variable width content

Use classes to size columns based on the natural width of their content.

1 of 3

Variable width content

3 of 3

1 of 3

Variable width content

3 of 3

Equal-width multi-row

Create equal-width columns that span multiple rows by inserting a where you want the columns to break to a new line. Make the breaks responsive by mixing the with some responsive display utilities.

col
col

col
col

Z-index

Several Bootstrap components utilize , the CSS property that helps control layout by providing a third axis to arrange content. We utilize a default z-index scale in Bootstrap that’s been designed to properly layer navigation, tooltips and popovers, modals, and more.

These higher values start at an arbitrary number, high and specific enough to ideally avoid conflicts. We need a standard set of these across our layered components—tooltips, popovers, navbars, dropdowns, modals—so we can be reasonably consistent in the behaviors. There’s no reason we couldn’t have used + or +.

We don’t encourage customization of these individual values; should you change one, you likely need to change them all.

To handle overlapping borders within components (e.g., buttons and inputs in input groups), we use low single digit values of , , and for default, hover, and active states. On hover/focus/active, we bring a particular element to the forefront with a higher value to show their border over the sibling elements.

Поддержка браузерами

Прежде чем мы перейдем к ключевым изменениям новой версии Bootstrap, давайте рассмотрим поддержку браузерами. Если вы используете Bootstrap 4 или более старую версию платформы Bootstrap, вам может потребоваться настроить уровень поддержки при переходе на Bootstrap 5. Поддержка Internet Explorer 10 и 11 была официально исключена из новой версии. Теперь поддерживаемые браузеры — это Microsoft Edge вместе с другими наиболее популярными браузерами, такими как Google Chrome и Firefox, включая последнюю версию Firefox с расширенной поддержкой (ESR)

Обратите внимание на то, что прокси-браузеры (такие как Opera Mini, Opera Mobile’s Turbo mode, Amazon Silk, UC Browser Mini) не поддерживаются. Bootstrap 5 также может хорошо работать в Chromium и Chrome для Linux, а также Firefox для Linux, но официально это не указано

Кроме того, альтернативные браузеры, которые используют последнюю версию WebKit, Blink или Gecko, напрямую или через WebView API, официально не поддерживаются.

Когда дело доходит до поддержки мобильных устройств, минимальная поддерживаемая версия iOS — это версия 7 и выше. Для Android это версия 6 и выше в браузере и WebView. Более старые версии Android и iOS официально не поддерживаются. Некоторые свойства CSS, такие как hidden; для элемента <body> весьма ограничены в iOS и Android.

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

Bootstrap 5 vs. Bootstrap 3 & 4

This tutorial follows Bootstrap 3, which was released in 2013. However, we also cover newer versions; Bootstrap 4 (released 2018) and Bootstrap 5 (released 2021).

Bootstrap 5 is the newest version of Bootstrap;
with new components, faster stylesheets, more responsiveness etc. It supports the latest, stable releases of all major browsers and
platforms. However, Internet Explorer 11 and down is not supported.

The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that
Bootstrap 5 has switched to JavaScript instead of jQuery.

Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes,
and it is perfectly safe to continue to use them. However, new features will NOT be added to
them.

Сетка и колонки

Бутстрап для себя делит экран на 12 колонок, независимо от размера экрана. Даже маленький экран старого телефона Бутстрап разобьёт на 12 колонок и будет ими управлять. На этом холсте вы можете создавать блоки шириной с какое-то количество колонок. Например, чтобы написать текст на половину ширины экрана, нужно создать блок шириной 6 колонок.

Блоки живут не сами по себе, а как бы в таблицах. Вы говорите Бутстрапу: «Создай мне контейнер для блока, в контейнере — строку, внутри строки — колонку, а внутрь колонки — положи этот текст». Сейчас это выглядит странно, но позже вы привыкнете.

Строка заполняется ячейками слева направо. Когда кончается строка, можно создать новую строку и снова заполнить её ячейками разной ширины. Ширина ячеек выражается в колонках. Ячейка шириной на весь экран будет иметь ширину 12 колонок, на пол-экрана — 6 колонок. Чтобы разбить экран на три части по горизонтали, нужно 3 ячейки шириной по 4 колонки. Чтобы сделать сетку, как у обычного трёхколоночного сайта, попробуйте три ячейки: 2 колонки, 8 колонок, 2 колонки. 

Можно сказать Бутстрапу: «Когда экран маленький, эту колонку выводи на всю ширину, а ту вообще прячь». Например, у нас в левой колонке было меню сайта, в центральной — основной текст, а в правой — всякие вспомогательные ссылки. Тогда говорим левой колонке на мобилке вывестись на всю ширину, основной колонке — тоже на всю ширину, а правой — скрыться. Получится мобильная версия сайта.

И так можно долго куражиться. Если интересно, прочитайте документацию по сеткам Бутстрапа — там всё понятно по картинкам. 

Bootstrap Exercises

Bootstrap References

At W3Schools you will find a complete Bootstrap reference of all CSS classes,
Components, and JavaScript plugins — all with «Try it Yourself» examples:

Complete List of All Bootstrap ClassesPopular
Bootstrap CSS Tables
Bootstrap Components Glyphicons
Bootstrap JS Tooltip

We have made some Bootstrap Templates you can play around with. They are completely free to use:

Bootstrap 5 vs. Bootstrap 3 & 4

This tutorial follows Bootstrap 3, which was released in 2013. However, we also cover newer versions; Bootstrap 4 (released 2018) and Bootstrap 5 (released 2021).

Bootstrap 5 is the newest version of Bootstrap;
with new components, faster stylesheets, more responsiveness etc. It supports the latest, stable releases of all major browsers and
platforms. However, Internet Explorer 11 and down is not supported.

The main differences between Bootstrap 5 and Bootstrap 3 & 4, is that
Bootstrap 5 has switched to JavaScript instead of jQuery.

Note: Bootstrap 3 and Bootstrap 4 is still supported by the team for critical bugfixes and documentation changes,
and it is perfectly safe to continue to use them. However, new features will NOT be added to
them.

Did You Know?

W3.CSS is an excellent alternative to Bootstrap.

W3.CSS is smaller, faster, and easier to use.

If you want to learn W3.CSS, go to our W3.CSS
Tutorial.

❮ Home
Next ❯

Исходный код Bootstrap 5

Прежде чем мы перейдем к углубленному рассмотрению новой версии Bootstrap, давайте посмотрим на исходный код Bootstrap 5. Если скачать исходный код здесь, и распаковать файл, вы найдете много файлов, но мы сосредоточимся только на папке dist, внутри которой находится ядро файлов CSS и JS.

Как можно увидеть на изображениях приведенных выше, здесь много файлов CSS и JavaScript. Однако вам понадобятся только два из них, чтобы вручную воспользоваться функциями Bootstrap 5 в минимизированной версии: bootstrap.min.css и bootstrap.min.js. Если вы хотите использовать неминимизированную версию, вам понадобятся файлы bootstrap.css и bootstrap.js.

Пропуск навигации

Благодаря давнему недостатки/ошибки в Chrome (см. вопрос 262171 в хром багтрекер) и Internet Explorer (см. эту статью на ссылки и фокус того), Вы должны убедиться, что цель вашей ссылке пропустить хотя бы программно фокусируемый, добавив .

Кроме того, может потребоваться явно подавляет видимый фокусировки на мишени (в частности, хром в настоящее время также устанавливает фокус на элементах с при щелчке мышкой) с .

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

Containers

Containers are the most basic layout element in Bootstrap and are required when using our default grid system. Containers are used to contain, pad, and (sometimes) center the content within them. While containers can be nested, most layouts do not require a nested container.

Bootstrap comes with three different containers:

  • , which sets a at each responsive breakpoint
  • , which is at all breakpoints
  • , which is until the specified breakpoint

The table below illustrates how each container’s compares to the original and across each breakpoint.

See them in action and compare them in our .

Extra small<576px Small≥576px Medium≥768px Large≥992px Extra large≥1200px
100% 540px 720px 960px 1140px
100% 540px 720px 960px 1140px
100% 100% 720px 960px 1140px
100% 100% 100% 960px 1140px
100% 100% 100% 100% 1140px
100% 100% 100% 100% 100%

Responsive

Responsive containers are new in Bootstrap v4.4. They allow you to specify a class that is 100% wide until the specified breakpoint is reached, after which we apply s for each of the higher breakpoints. For example, is 100% wide to start until the breakpoint is reached, where it will scale up with , , and .

Two Basic Bootstrap Pages

The following example shows the code for a basic Bootstrap page (with a responsive fixed width container):

Example

<!DOCTYPE html><html lang=»en»><head>  <title>Bootstrap Example</title>  <meta charset=»utf-8″>  <meta name=»viewport» content=»width=device-width, initial-scale=1″>  <link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css»>
 
<script src=»https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js»></script>
 
<script src=»https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js»></script>
</head><body><div class=»container»>  <h1>My First Bootstrap Page</h1>  <p>This is some text.</p> </div></body></html>

The following example shows the code for a basic Bootstrap page (with a full width container):

Example

<!DOCTYPE html><html lang=»en»><head>  <title>Bootstrap Example</title>  <meta charset=»utf-8″>  <meta name=»viewport» content=»width=device-width, initial-scale=1″>  <link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css»>
  <script src=»https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js»></script>
 
<script src=»https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js»></script></head><body><div class=»container-fluid»>  <h1>My First Bootstrap Page</h1>  <p>This is some text.</p> </div></body></html>

❮ Previous
Next ❯

CSPs and embedded SVGs

Several Bootstrap components include embedded SVGs in our CSS to style components consistently and easily across browsers and devices. For organizations with more strict CSP configurations, we’ve documented all instances of our embedded SVGs (all of which are applied via ) so you can more thoroughly review your options.

  • Close button (used in alerts and modals)

Based on community conversation, some options for addressing this in your own codebase include replacing the URLs with locally hosted assets, removing the images and using inline images (not possible in all components), and modifying your CSP. Our recommendation is to carefully review your own security policies and decide on a best path forward, if necessary.

Сообщество

Будьте в курсе развития Bootstrap и обращайтесь к сообществу с помощью этих полезных ресурсов.

  • Обсуждайте в чате Telegram @getbootstrap_ru.
  • Читайте и подписывайтесь на Официальный блог Bootstrap.
  • Присоединиться к официальной комнате Slack.
  • Общайтесь с другими Bootstrappers в IRC. На сервере , в канале .
  • Справку по реализации можно найти на сайте Stack Overflow (с тегом ).
  • Разработчикам следует использовать ключевое слово в пакетах, которые изменяют или расширяют функциональность Bootstrap при распространении через npm или аналогичные механизмы доставки для максимальной узнаваемости.

Вы также можете следить за @getbootstrap в Твиттере, чтобы следить за последними слухами и потрясающими музыкальными клипами.

Какую версию Bootstrap выбрать

Для разработки большинства веб-проектов лучше использовать последнюю версию Bootstrap в выбранной ветке.

На текущий момент:

  • в v5 — это 5.1.3 (скачать);
  • в v4 — это 4.6.1 (скачать);
  • в v3 — это 3.4.1 (скачать).

Bootstrap 5 рекомендуется для проектов, которые будут использоваться только в современных браузерах (поддержка IE и других браузеров не нужна). В других случаях — Bootstrap 4.

Что нового в Bootstrap 5:

  • нет зависимости от библиотеки jQuery, все плагины переписаны на чистом JavaScript;
  • библиотека Popper обновлена до v2.x с v1.x;
  • не поддерживаются Internet Explorer 10 и 11, Microsoft Edge <16, Firefox <60, Safari <10, iOS Safari <10, Chrome <60 и Android <6;
  • добавлен новый брекпойнт в сетку ( для 1400px и выше);
  • новые классы , и для указания горизонтальных и вертикальных отступов между ячейками;
  • добавлен новый компонент offcanvas;
  • удален компонент Media, его реализацию предлагают выполнять с помощью утилитных классов Bootstrap;
  • улучшен раздел по формам в документации, и добавлена возможность создания в плавающего .

Третью версию в основном имеет смысл использовать, если нужна поддержка «старых» браузеров (IE8 и IE9).

Основные отличия Bootstrap 4 от Bootstrap 3:

  • не поддерживает IE8, IE9 и iOS6 (v4 теперь только IE10+ и iOS7+);
  • сетка и другие компоненты построены на флексах, а не на float;
  • исходный код стилей написан на Sass, а не на Less;
  • размеры, указываются в rem и em, а не в px;
  • размер шрифта увеличен с 14px до 16px;
  • увеличено количество брекпойнтов в сетки (в v4 — 5, в v3 — 4);
  • удалены компоненты Panels, Thumbnails и Wells, вместо них добавлен Cards;
  • удалены иконочный шрифт Glyphicons и jQuery плагин Affix;
  • обновлены почти все компоненты;
  • работа всплывающих подсказок (Tooltips) и блоков с контентов (Popovers) построена на библиотеке Popper JS.

Компоненты Bootstrap 3 в IE8 и некоторых других версиях отображаются без градиентов, теней и закруглённых углов. Это связано с тем, что в них нет поддержки используемых для этих целей CSS3 свойств.

Community

Stay up to date on the development of Bootstrap and reach out to the community with these helpful resources.

  • Read and subscribe to The Official Bootstrap Blog.
  • Join the official Slack room.
  • Chat with fellow Bootstrappers in IRC. On the server, in the channel.
  • Implementation help may be found at Stack Overflow (tagged ).
  • Developers should use the keyword on packages that modify or add to the functionality of Bootstrap when distributing through npm or similar delivery mechanisms for maximum discoverability.

You can also follow @getbootstrap on Twitter for the latest gossip and awesome music videos.

Quick start

Looking to quickly add Bootstrap to your project? Use jsDelivr, a free open source CDN. Using a package manager or need to download the source files? Head to the downloads page.

JS

Many of our components require the use of JavaScript to function. Specifically, they require jQuery, Popper.js, and our own JavaScript plugins. We use jQuery’s slim build, but the full version is also supported.

Place one of the following s near the end of your pages, right before the closing tag, to enable them. jQuery must come first, then Popper.js, and then our JavaScript plugins.

Bundle

Include everything you need in one script with our bundle. Our and include Popper, but not jQuery. For more information about what’s included in Bootstrap, please see our section.

Components

Curious which components explicitly require jQuery, our JS, and Popper.js? Click the show components link below. If you’re unsure about the page structure, keep reading for an example page template.

Show components requiring JavaScript

  • Alerts for dismissing
  • Buttons for toggling states and checkbox/radio functionality
  • Carousel for all slide behaviors, controls, and indicators
  • Collapse for toggling visibility of content
  • Dropdowns for displaying and positioning (also requires Popper.js)
  • Modals for displaying, positioning, and scroll behavior
  • Navbar for extending our Collapse plugin to implement responsive behavior
  • Toasts for displaying and dismissing
  • Tooltips and popovers for displaying and positioning (also requires Popper.js)
  • Scrollspy for scroll behavior and navigation updates

Sass

When using Bootstrap’s source Sass files, you have the option of using Sass variables and mixins to create custom, semantic, and responsive page layouts. Our predefined grid classes use these same variables and mixins to provide a whole suite of ready-to-use classes for fast responsive layouts.

Variables

Variables and maps determine the number of columns, the gutter width, and the media query point at which to begin floating columns. We use these to generate the predefined grid classes documented above, as well as for the custom mixins listed below.

Example usage

You can modify the variables to your own custom values, or just use the mixins with their default values. Here’s an example of using the default settings to create a two-column layout with a gap between.

Main content
Secondary content

Две основных страницы Bootstrap 4

В следующем примере показан код для базовой страницы Bootstrap 4 (с адаптивным контейнером фиксированной ширины):

Пример контейнера

<!DOCTYPE html><html lang=»en»><head>  <title>Bootstrap
4 Пример</title>  <meta charset=»utf-8″>  <meta name=»viewport» content=»width=device-width, initial-scale=1″>  <link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css»>
 
<script src=»https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js»></script> 
<script src=»https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.2/umd/popper.min.js»></script>
 
<script src=»https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js»></script>
</head><body><div class=»container»>  <h1>Моя первая Bootstrap страница</h1>  <p>Здесь какой-то текст.</p> </div></body></html>

В следующем примере показан код для базовой страницы Bootstrap 4 (с контейнером полной ширины):

Пример жидкого контейнера

<!DOCTYPE html><html lang=»en»><head>  <title>Bootstrap
4 Пример</title>  <meta charset=»utf-8″>  <meta name=»viewport» content=»width=device-width, initial-scale=1″>  <link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css»>
  <script src=»https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js»></script> 
<script src=»https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.2/umd/popper.min.js»></script>
 
<script src=»https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js»></script></head><body><div class=»container-fluid»>  <h1>Моя первая Bootstrap страница</h1>  <p>Здесь какой-то текст.</p> </div></body></html>

❮ Prev
Next ❯

Button plugin

The button plugin allows you to create simple on/off toggle buttons.

Visually, these toggle buttons are identical to the . However, they are conveyed differently by assistive technologies: the checkbox toggles will be announced by screen readers as “checked”/“not checked” (since, despite their appearance, they are fundamentally still checkboxes), whereas these toggle buttons will be announced as “button”/“button pressed”. The choice between these two approaches will depend on the type of toggle you are creating, and whether or not the toggle will make sense to users when announced as a checkbox or as an actual button.

Toggle states

Add to toggle a button’s state. If you’re pre-toggling a button, you must manually add the class and to ensure that it is conveyed appropriately to assistive technologies.

Toggle button
Active toggle button
Disabled toggle button

Disabled toggle link

Methods

You can create a button instance with the button constructor, for example:

Method Description
Toggles push state. Gives the button the appearance that it has been activated.
Destroys an element’s button. (Removes stored data on the DOM element)
Static method which allows you to get the button instance associated to a DOM element, you can use it like this:
Static method which returns a button instance associated to a DOM element or create a new one in case it wasn’t initialized.
You can use it like this:

For example, to toggle all buttons

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector