Contents

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

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

Community

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

  • Follow @getbootstrap on Twitter.
  • 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 which 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.

Как это работает

На высоком уровне, блочная система работает так:

  • Существует три основных компонента—контейнера, строки и столбцы.
  • Контейнеры— для фиксированной ширины или на полную ширину—центрирует содержание вашего сайта и помогает выровнять содержание блока.
  • «Rows» — горизонтальные группы столбцов, которые обеспечивают чтобы столбцы выстроились правильно.
  • Контент должен быть помещен в столбцах, и только колонки могут быть непосредственными потомками строк.
  • Классы столбце указано количество столбцов, которые вы хотите использовать из 12 возможных в ряду. Так что если вы хотите три равные ширины столбцов, нужно использовать .
  • Столбец устанавливаются в процентах, так они всегда изменчивый и размерами по отношению к родительскому элементу.
  • Столбцы имеют горизонтальную для создания промежутка между отдельными столбцами.
  • Есть пять грид уровней, по одному для каждой : сверхмалые, малые, средние, большие, и очень большие.
  • Грид уровни основываются на минимальной ширине, то есть они применяются к ярусу и всем, кто выше его (например, применим для малых, средних, больших, и очень больших устройств).
  • Вы можете использовать предопределенные грид классов или Sass примеси для более семантической разметки.

Звучит хорошо? Отлично, давайте перейдем посмотрев все это на примерах.

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, 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, and then our JavaScript plugins.

Bundle

Include every Bootstrap JavaScript plugin with one of our two bundles. Both and include Popper for our tooltips and popovers, but not jQuery. Include jQuery first, then a Bootstrap JavaScript bundle. For more information about what’s included in Bootstrap, please see our section.

Separate

If you decide to go with the separate scripts solution, Popper must come first (if you’re using tooltips or popovers), and then our JavaScript plugins.

Components

Curious which components explicitly require jQuery, our JavaScript, and Popper? 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)
  • Modals for displaying, positioning, and scroll behavior
  • Navbar for extending our Collapse plugin to implement responsive behavior
  • Tooltips and popovers for displaying and positioning (also requires Popper)
  • Scrollspy for scroll behavior and navigation updates

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.

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.

Customizing the grid

Using our built-in grid Sass variables and maps, it’s possible to completely customize the predefined grid classes. Change the number of tiers, the media query dimensions, and the container widths—then recompile.

Columns and gutters

The number of grid columns can be modified via Sass variables. is used to generate the widths (in percent) of each individual column while allows breakpoint-specific widths that are divided evenly across and for the column gutters.

Grid tiers

Moving beyond the columns themselves, you may also customize the number of grid tiers. If you wanted just four grid tiers, you’d update the and to something like this:

When making any changes to the Sass variables or maps, you’ll need to save your changes and recompile. Doing so will output a brand new set of predefined grid classes for column widths, offsets, and ordering. Responsive visibility utilities will also be updated to use the custom breakpoints. Make sure to set grid values in (not , , or ).

Bootstrap CDN

If you don’t want to download and host Bootstrap yourself, you can include it from a CDN (Content Delivery Network).

MaxCDN provides CDN support for Bootstrap’s CSS and JavaScript. You must also include jQuery:

MaxCDN:

<!— Latest compiled and minified CSS —><link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css»><!— jQuery library —><script src=»https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js»></script><!— Latest compiled JavaScript —><script src=»https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js»></script>

One advantage of using the Bootstrap CDN:
Many users already have downloaded
Bootstrap from MaxCDN when visiting
another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time.
Also, most CDN’s will make sure that once a user requests a file from it, it will be served
from the server closest to them, which also leads to faster loading time.

jQueryBootstrap uses jQuery for JavaScript plugins (like modals, tooltips, etc). However, if you just use the
CSS part of Bootstrap, you don’t need jQuery.

Важные глобальные переменные

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

В HTML5 Тип документа

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

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

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

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

Размерность блоков

Для более простой калибровки в CSS, то переключатель глобальный значение для . Это гарантирует , не влияет на конечный вычисляется Ширина элемента, но это может вызвать проблемы с некоторыми программами сторонних разработчиков, таких как карты Google и Google пользовательского поиска.

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

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

Узнать больше о модель и размер в CSS трюки.

Normalize.css

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

Community

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

  • Follow @getbootstrap on Twitter.
  • 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 which 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.

Grid options

Bootstrap’s grid system can adapt across all six default breakpoints, and any breakpoints you customize. The six default grid tiers are as follow:

  • Extra small (xs)
  • Small (sm)
  • Medium (md)
  • Large (lg)
  • Extra large (xl)
  • Extra extra large (xxl)

As noted above, each of these breakpoints have their own container, unique class prefix, and modifiers. Here’s how the grid changes across these breakpoints:

xs<576px sm≥576px md≥768px lg≥992px xl≥1200px xxl≥1400px
Container None (auto) 540px 720px 960px 1140px 1320px
Class prefix
# of columns 12
Gutter width 1.5rem (.75rem on left and right)
Custom gutters Yes
Nestable
Column ordering

Быстрый старт

Хотите быстро добавить Bootstrap в свой проект? Используйте jsDelivr, бесплатный CDN с открытым исходным кодом. Используете менеджер пакетов или вам нужно скачать исходные файлы? Перейдите на страницу загрузок.

Скрипты

Многие из наших компонентов требуют использования JavaScript для работы. В частности, для них требуются наши собственные плагины JavaScript и Popper. Поместите один из следующих в конце Ваших страниц, прямо перед закрывающим тегом , чтобы включить их.

Связка

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

Раздельно

Если Вы решите использовать отдельное решение для сценариев, сначала должен быть Popper.js (если Вы используете всплывающие подсказки или всплывающие окна), а затем наши плагины JavaScript.

Компоненты

Интересно, какие компоненты явно требуют нашего JavaScript и Popper? Кликните на ссылку “Показать компоненты” ниже. Если Вы совсем не уверены в общей структуре страницы, продолжайте читать, чтобы найти образец шаблона страницы.

Показать компоненты, требующие JavaScript

  • Alerts (Уведомления) для отклонения
  • Buttons (Кнопки) для переключения состояний и функционала флажка/радио
  • Carousel (Карусель) для любого поведения слайдов, элементов управления и индикаторов
  • Collapse (Сворачиваемое) для переключения видимости содержимого
  • Dropdowns (Выпадающие списки) для отображения и позиционирования (также требуется Popper)
  • Modals (Модальные окна) для отображения, позиционирования и прокрутки
  • Navbar (Панель навигации) для расширения нашего плагина Сворачиваемое для реализации адаптивного поведения
  • Toasts (Тосты) для показа и отклонения
  • Tooltips (Всплывающие подсказки) и popovers (всплывающие окна) для отображения и позиционирования (также требуется Popper)
  • Scrollspy (Отслеживание прокрутки) для поведения прокрутки и обновлений навигации

Internet Explorer 8 и Respond.js

Примите во внимание следующие оговорки, при использовании Respond.js в вашей среде разработки, в рабочей среде Internet Explorer 8

Respond.js и кросс-доменный CSS

Если вы храните Respond.js и CSS на разных (суб)доменах (например, на CDN) — это требует некоторых дополнительных установок. для уточнений.

Respond.js и

Через правила безопасности браузера, Respond.js не работает при просмотре через протокол (например, когда вы открываете HTML файл локально). Чтобы протестировать настройки чувствительности в IE8, просматривайте ваши страницы через HTTP(S). для уточнений.

Respond.js и

Respond.js не работает с CSS, на которые ссылаются как . В частности, некоторые конфигурации Drupal, как известно, используют . для уточнений.

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.

Изменение визуального порядка следования адаптивных блоков

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

Изменить визуальный порядок следования адаптивного блока в Bootstrap 4 выполняется посредством класса . Этот класс предназначен для контрольной точки . Если порядок элемента нужно определить не для контрольной точки , а для , , или , то используется следующий вариант данного класса:

order-{breakpoint}-{visual_number}

Вместо необходимо указать число от 1 до 12.

Это число и определяет то, как элементы будут визуально следовать на странице. А именно все адаптивные элементы будут визуально следовать в порядке возрастания этих номеров. Если элементу не установлен класс , то по умолчанию он имеет значение 0.

Например, изменим порядок следования двух адаптивных блоков:

<div class="row">
  <div class="col">
    Первый (не упорядоченный, без класса order-)
    <!-- По умолчанию order, равно 0, поэтому он и первый-->
  </div>
  <div class="col order-12">
    Второй, но будет отображаться последним
  </div>
  <div class="col order-1">
    Третий, но будет отображаться вторым
  </div>
</div>

Ещё один пример (с использованием адаптивных классов ):

<div class="row">
  <div class="col-md-8 order-2 order-md-1">
    Первый (на xs, sm будет отображаться вторым)
  </div>
  <div class="col-md-4 order-1 order-md-2">
    Второй (на xs, sm будет отображаться первым)
  </div>
</div>

Кроме чисел (по умолчанию от 1 до 12) можно ещё использовать слова и . Эти классы (, , , ) позволяют соответственно визуально сместить элемент в начало или конец.

Классы и оказывают своё действие посредством установки элементу CSS свойства со значением -1 (), а классы и — CSS свойства со значением 13 ().

Перепишем вышеприведённый пример с использованием классов , в которых используются ключевые слова и :

<div class="row">
  <div class="col-md-8 order-last order-md-first">
    Первый (на xs, sm будет отображаться последним)
  </div>
  <div class="col-md-4 order-first order-md-last">
    Последний (на xs, sm будет отображаться первым)
  </div>
</div>

Пример с использованием классов как с числом, так и со словами и :

<div class="row">
  <div class="col-3 order-sm-last order-md-1">#1 (XS), #LAST (SM), #1 (MD, LG и XL)</div>
  <div class="col-3 order-md-7">#2 (XS), #7 (MD, LG и XL)</div>
  <div class="col-3 order-md-6">#3 (XS), #6 (MD, LG и XL)</div>
  <div class="col-3 order-md-5">#4 (XS), #5 (MD, LG и XL)</div>
  <div class="col-3 order-md-4">#5 (XS), #4 (MD, LG и XL)</div>
  <div class="col-3 order-md-3">#6 (XS), #3 (MD, LG и XL)</div>
  <div class="col-3 order-md-2">#7 (XS), #2 (MD, LG и XL)</div>
  <div class="col-3 order-sm-first order-md-8">#8 (XS), #FIRST (SM), #8 (MD, LG и XL)</div>
</div>

Reordering

Order classes

Use classes for controlling the visual order of your content. These classes are responsive, so you can set the by breakpoint (e.g., ). Includes support for through across all five grid tiers.

First, but unordered

Second, but last

Third, but first

There are also responsive and classes that change the of an element by applying and (), respectively. These classes can also be intermixed with the numbered classes as needed.

First, but last

Second, but unordered

Third, but first

Offsetting columns

You can offset grid columns in two ways: our responsive grid classes and our margin utilities. Grid classes are sized to match columns while margins are more useful for quick layouts where the width of the offset is variable.

Offset classes

Move columns to the right using classes. These classes increase the left margin of a column by columns. For example, moves over four columns.

.col-md-4
.col-md-4 .offset-md-4

.col-md-3 .offset-md-3
.col-md-3 .offset-md-3

.col-md-6 .offset-md-3

In addition to column clearing at responsive breakpoints, you may need to reset offsets. See this in action in the grid example.

.col-sm-5 .col-md-6
.col-sm-5 .offset-sm-2 .col-md-6 .offset-md-0

.col-sm-6 .col-md-5 .col-lg-6
.col-sm-6 .col-md-5 .offset-md-2 .col-lg-6 .offset-lg-0

Margin utilities

With the move to flexbox in v4, you can use margin utilities like to force sibling columns away from one another.

.col-md-4
.col-md-4 .ml-auto

.col-md-3 .ml-md-auto
.col-md-3 .ml-md-auto

.col-auto .mr-auto
.col-auto

Quick start

Looking to quickly add Bootstrap to your project? Use BootstrapCDN, provided for free by the folks at StackPath. 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. Place 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.

We use jQuery’s slim build, but the full version is also supported.

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

Our and include Popper, but not jQuery. For more information about what’s included in Bootstrap, please see our section.

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
  • Tooltips and popovers for displaying and positioning (also requires Popper.js)
  • Scrollspy for scroll behavior and navigation updates

Печать

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

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

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

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

Sass примеси

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

Переменные

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

Смешивания

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

Примеры использования

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

Увидеть его в действии в это привело к примеру.

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 4 с помощью служебных flex-классов.

Вертикальное выравнивание адаптивных блоков

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

  • (относительно начала линии);
  • (по центру);
  • (относительно конца).

Например, выровняем все адаптивные блоки по центру линии ряда:

<div class="row align-items-center">
    <div class="col"> 1/2 </div>
    <div class="col"> 2/2 </div>
</div>

По умолчанию адаптивные элементы занимают всю высоту линии ряда, в которой они расположены.

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

  • (относительно начала линии);
  • (по центру);
  • (относительно конца).

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

Например, выравниваем адаптивный блок 2 по нижнему краю линии:

<div class="row align-items-center">
    <div class="col"> (1) </div>
    <div class="col align-self-end"> (2) </div>
</div>

Горизонтальное выравнивание адаптивных блоков

Для выравнивания адаптивных блоков в горизонтальном направлении предназначены следующие классы:

  • (относительно начала линии ряда — по умолчанию);
  • (по центру);
  • (относительно конца линии);
  • (равномерно, с учётом пространства перед первым и последним адаптивным блоком);
  • (равномерно, с одинаковым пространством между адаптивными блоками).

Например, распределим адаптивные блоки в горизонтальном направлении равномерно:

<div class="row justify-content-around">
    <div class="col-4"> (1) </div>
    <div class="col-4"> (2) </div>
</div>

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.

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

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

Adblock
detector