Bootstrap 4. сетка. подробное руководство

Смещение адаптивных блоков

В Bootstrap 4 смещение адаптивных блоков можно выполнить с помощью:


  • классов offset (на определённое количество колонок);
  • служебных (утилитных) margin классов.

Классы offset

Классы offset предназначены для смещения адаптивных блоков вправо на определённое количество колонок.

Данные классы имеют следующий синтаксис:

оffset-{1} или offset-{breakpoint}-{1}

– контрольная точка, начиная с которой к данному блоку будет применено смещение (если она не указана, то смещение будет применено, начиная с самых крохотных устройств).

– величина смещения, указываемая с помощью количества колонок Bootstrap.

В качестве примера установим смещение адаптивным блокам так, как это показано на рисунке.

<div class="row">
  <div class="col-4"> (1) </div>
  <div class="col-4 offset-4"> (2) </div>
</div>
<div class="row">
  <div class="col-3 offset-3"> (1) </div>
  <div class="col-3 offset-3"> (2) </div>
</div>
<div class="row">
  <div class="col-6 offset-3"> (1) </div>
</div>  

Смещение с помощью margin классов

В четвертой версии Bootstrap устанавливать смещение адаптивным блокам также можно с помощью margin отступов (margin-left: auto и (или) margin-right: auto). Эта вариант смещения появился благодаря тому, что сетка в новой версии Bootstrap (4) основывается на CSS Flexbox.

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

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

<div class="row">
  <div class="col-4"> (1) </div>
  <div class="col-4 ml-auto"> (2) </div>
</div>
<div class="row">
  <div class="col-3"> (1) </div>
  <div class="col-3 ml-auto mr-auto"> (2) </div>
  <div class="col-3"> (3)</div>
</div>
<div class="row">
  <div class="col-4 ml-auto mr-auto"> (1) </div>
  <div class="col-4 ml-auto mr-auto"> (2) </div>
</div>  

Modals, navbars, and virtual keyboards

Overflow and scrolling

Support for on the element is quite limited in iOS and Android. To that end, when you scroll past the top or bottom of a modal in either of those devices’ browsers, the content will begin to scroll. See Chrome bug #175502 (fixed in Chrome v40) and WebKit bug #153852.

iOS text fields and scrolling

As of iOS 9.3, while a modal is open, if the initial touch of a scroll gesture is within the boundary of a textual or a , the content underneath the modal will be scrolled instead of the modal itself. See WebKit bug #153856.

Virtual keyboards

Also, note that if you’re using a fixed navbar or using inputs within a modal, iOS has a rendering bug that doesn’t update the position of fixed elements when the virtual keyboard is triggered. A few workarounds for this include transforming your elements to or invoking a timer on focus to try to correct the positioning manually. This is not handled by Bootstrap, so it is up to you to decide which solution is best for your application.

Navbar Dropdowns

The element isn’t used on iOS in the nav because of the complexity of z-indexing. Thus, to close dropdowns in navbars, you must directly click the dropdown element (or ).

Alignment

Use flexbox alignment utilities to vertically and horizontally align columns. Internet Explorer 10-11 do not support vertical alignment of flex items when the flex container has a as shown below.

Vertical alignment

One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns

One of three columns One of three columns One of three columns

Horizontal alignment

One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns

No gutters

The gutters between columns in our predefined grid classes can be removed with . This removes the negative s from and the horizontal from all immediate children columns.

Here’s the source code for creating these styles. Note that column overrides are scoped to only the first children columns and are targeted via attribute selector. While this generates a more specific selector, column padding can still be further customized with spacing utilities.

Need an edge-to-edge design? Drop the parent or .

In practice, here’s how it looks. Note you can continue to use this with all other predefined grid classes (including column widths, responsive tiers, reorders, and more).

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

Column wrapping

If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line.

.col-9 .col-4Since 9 + 4 = 13 > 12, this 4-column-wide div gets wrapped onto a new line as one contiguous unit. .col-6Subsequent columns continue along the new line.

Column breaks

Breaking columns to a new line in flexbox requires a small hack: add an element with wherever you want to wrap your columns to a new line. Normally this is accomplished with multiple s, but not every implementation method can account for this.

.col-6 .col-sm-3 .col-6 .col-sm-3

.col-6 .col-sm-3 .col-6 .col-sm-3

You may also apply this break at specific breakpoints with our responsive display utilities.

.col-6 .col-sm-4 .col-6 .col-sm-4

.col-6 .col-sm-4 .col-6 .col-sm-4

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 multi-line

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

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 your target browsers don’t fall into the buggy versions.


col col col col

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

Internet Explorer 10 in Windows 8 and Windows Phone 8

Internet Explorer 10 doesn’t differentiate device width from viewport width, and thus doesn’t properly apply the media queries in Bootstrap’s CSS. Normally you’d just add a quick snippet of CSS to fix this:

However, this doesn’t work for devices running Windows Phone 8 versions older than Update 3 (a.k.a. GDR3), as it causes such devices to show a mostly desktop view instead of narrow «phone» view. To address this, you’ll need to include the following CSS and JavaScript to work around the bug.

For more information and usage guidelines, read Windows Phone 8 and Device-Width.

As a heads up, we include this in all of Bootstrap’s documentation and examples as a demonstration.

JavaScript behavior

Triggers

Enable dismissal of an alert via JavaScript:

Or with attributes on a button within the alert, as demonstrated above:

Note that closing an alert will remove it from the DOM.

Methods

Method Description
Makes an alert listen for click events on descendant elements which have the attribute. (Not necessary when using the data-api’s auto-initialization.)
Closes an alert by removing it from the DOM. If the and classes are present on the element, the alert will fade out before it is removed.
Destroys an element’s alert.

Events

Bootstrap’s alert plugin exposes a few events for hooking into alert functionality.

Event Description
This event fires immediately when the instance method is called.
This event is fired when the alert has been closed (will wait for CSS transitions to complete).

Documentation

Our documentation received an upgrade across the board as well. Here’s the low down:

  • We’re still using Jekyll, but we have plugins in the mix:
    • is used to efficiently list out the entries on our browser bugs page.
    • is a custom fork of the default plugin, allowing for easier example-code handling.
    • is a similar custom fork of that, but designed for our special docs callouts.
    • is used to to render Markdown snippets within HTML elements like tables.
    • jekyll-toc is used to generate our table of contents.
  • All docs content has been rewritten in Markdown (instead of HTML) for easier editing.
  • Pages have been reorganized for simpler content and a more approachable hierarchy.
  • We moved from regular CSS to SCSS to take full advantage of Bootstrap’s variables, mixins, and more.

Responsive utilities

All variables have been removed in v4.0.0. Use the , , or Sass mixins or the Sass map instead.

Our responsive utility classes have largely been removed in favor of explicit utilities.

  • The and classes have been removed because they conflicted with jQuery’s and methods. Instead, try toggling the attribute or use inline styles like and .
  • All classes have been removed, save for the print utilities which have been renamed.
    • Removed from v3:
    • Removed from v4 alphas:
  • Print utilities no longer start with or , but with .
    • Old names: , , ,
    • New classes: , , ,

Rather than using explicit classes, you make an element visible by simply not hiding it at that screen size. You can combine one class with one class to show an element only on a given interval of screen sizes (e.g. shows the element only on medium and large devices).

Note that the changes to the grid breakpoints in v4 means that you’ll need to go one breakpoint larger to achieve the same results. The new responsive utility classes don’t attempt to accommodate less common cases where an element’s visibility can’t be expressed as a single contiguous range of viewport sizes; you will instead need to use custom CSS in such cases.

Usage

Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the class on the parent list item. The attribute is relied on for closing dropdown menus at an application level, so it’s a good idea to always use it.

On touch-enabled devices, opening a dropdown adds empty () handlers to the immediate children of the element. This admittedly ugly hack is necessary to work around a quirk in iOS’ event delegation, which would otherwise prevent a tap anywhere outside of the dropdown from triggering the code that closes the dropdown. Once the dropdown is closed, these additional empty handlers are removed.

Via JavaScript

Call the dropdowns via JavaScript:

still required

Regardless of whether you call your dropdown via JavaScript or instead use the data-api, is always required to be present on the dropdown’s trigger element.

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to , as in .

Name Type Default Description
offset number | string | function

Offset of the dropdown relative to its target.

When a function is used to determine the offset, it is called with an object containing the offset data as its first argument. The function must return an object with the same structure. The triggering element DOM node is passed as the second argument.

For more information refer to Popper.js’s .

flip boolean true Allow Dropdown to flip in case of an overlapping on the reference element. For more information refer to Popper.js’s .
boundary string | element ‘scrollParent’ Overflow constraint boundary of the dropdown menu. Accepts the values of , , , or an HTMLElement reference (JavaScript only). For more information refer to Popper.js’s .
reference string | element ‘toggle’ Reference element of the dropdown menu. Accepts the values of , , or an HTMLElement reference. For more information refer to Popper.js’s .
display string ‘dynamic’ By default, we use Popper.js for dynamic positioning. Disable this with .
popperConfig null | object null To change Bootstrap’s default Popper.js config, see

Note when is set to any value other than , the style is applied to the container.

Methods

Method Description
Toggles the dropdown menu of a given navbar or tabbed navigation.
Shows the dropdown menu of a given navbar or tabbed navigation.
Hides the dropdown menu of a given navbar or tabbed navigation.
Updates the position of an element’s dropdown.
Destroys an element’s dropdown.

Events

All dropdown events are fired at the ’s parent element and have a property, whose value is the toggling anchor element. and events have a property (only when the original event type is ) that contains an Event Object for the click event.

Event Description
This event fires immediately when the show instance method is called.
This event is fired when the dropdown has been made visible to the user (will wait for CSS transitions, to complete).
This event is fired immediately when the hide instance method has been called.
This event is fired when the dropdown has finished being hidden from the user (will wait for CSS transitions, to complete).

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.

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

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.

Skip navigation

If your navigation contains many links and comes before the main content in the DOM, add a link before the navigation (for a simple explanation, see this A11Y Project article on skip navigation links). Using the class will visually hide the skip link, and the class will ensure that the link becomes visible once focused (for sighted keyboard users).

Due to long-standing shortcomings/bugs in Chrome (see issue 262171 in the Chromium bug tracker) and Internet Explorer (see this article on in-page links and focus order), you will need to make sure that the target of your skip link is at least programmatically focusable by adding .

In addition, you may want to explicitly suppress a visible focus indication on the target (particularly as Chrome currently also sets focus on elements with when they are clicked with the mouse) with .

Note that this bug will also affect any other in-page links your site may be using, rendering them useless for keyboard users. You may consider adding a similar stop-gap fix to all other named anchors / fragment identifiers that act as link targets.

Menu alignment

By default, a dropdown menu is automatically positioned 100% from the top and along the left side of its parent. Add to a to right align the dropdown menu.

Heads up! Dropdowns are positioned thanks to Popper.js (except when they are contained in a navbar).

Right-aligned menu Action Another action Something else here

Responsive alignment

If you want to use responsive alignment, disable dynamic positioning by adding the attribute and use the responsive variation classes.

To align right the dropdown menu with the given breakpoint or larger, add .

Left-aligned but right aligned when large screen Action Another action Something else here

To align left the dropdown menu with the given breakpoint or larger, add and .

Right-aligned but left aligned when large screen Action Another action Something else here

Note that you don’t need to add a attribute to dropdown buttons in navbars, since Popper.js isn’t used in navbars.

Overview

Dropdowns are toggleable, contextual overlays for displaying lists of links and more. They’re made interactive with the included Bootstrap dropdown JavaScript plugin. They’re toggled by clicking, not by hovering; this is an intentional design decision.

Dropdowns are built on a third party library, Popper.js, which provides dynamic positioning and viewport detection. Be sure to include popper.min.js before Bootstrap’s JavaScript or use / which contains Popper.js. Popper.js isn’t used to position dropdowns in navbars though as dynamic positioning isn’t required.

If you’re building our JavaScript from source, it .

Validators

In order to provide the best possible experience to old and buggy browsers, Bootstrap uses CSS browser hacks in several places to target special CSS to certain browser versions in order to work around bugs in the browsers themselves. These hacks understandably cause CSS validators to complain that they are invalid. In a couple places, we also use bleeding-edge CSS features that aren’t yet fully standardized, but these are used purely for progressive enhancement.

These validation warnings don’t matter in practice since the non-hacky portion of our CSS does fully validate and the hacky portions don’t interfere with the proper functioning of the non-hacky portion, hence why we deliberately ignore these particular warnings.

Alignment

Use flexbox alignment utilities to vertically and horizontally align columns.

Vertical alignment

One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns One of three columns

One of three columns One of three columns One of three columns

Horizontal alignment

One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns One of two columns

No gutters

The gutters between columns in our predefined grid classes can be removed with . This removes the negative s from and the horizontal from all immediate children columns.


Here’s the source code for creating these styles. Note that column overrides are scoped to only the first children columns and are targeted via attribute selector. While this generates a more specific selector, column padding can still be further customized with spacing utilities.

Need an edge-to-edge design? Drop the parent or .

In practice, here’s how it looks. Note you can continue to use this with all other predefined grid classes (including column widths, responsive tiers, reorders, and more).

.col-12 .col-sm-6 .col-md-8 .col-6 .col-md-4

Column wrapping

If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line.

.col-9 .col-4Since 9 + 4 = 13 > 12, this 4-column-wide div gets wrapped onto a new line as one contiguous unit. .col-6Subsequent columns continue along the new line.

Column breaks

Breaking columns to a new line in flexbox requires a small hack: add an element with wherever you want to wrap your columns to a new line. Normally this is accomplished with multiple s, but not every implementation method can account for this.

.col-6 .col-sm-3 .col-6 .col-sm-3

.col-6 .col-sm-3 .col-6 .col-sm-3

You may also apply this break at specific breakpoints with our responsive display utilities.

.col-6 .col-sm-4 .col-6 .col-sm-4

.col-6 .col-sm-4 .col-6 .col-sm-4

Назначение Bootstrap сетки. Контрольные точки

Сетка Bootstrap 4 – это основная часть фреймворка. Она предназначена для создания адаптивных шаблонов.

Сетка Bootstrap 4 основывается на CSS Flexbox и медиа-запросах (CSS media queries). Чтобы понять, как она работает более точно, рекомендуется сначала изучить эти CSS технологии.

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

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

В Bootstrap изменения вида макета реализовано через медиа-запросы. Каждый медиа-запрос в Bootstrap строится на основании минимальной ширины viewport браузера. В Bootstrap ключевое значение ширины viewport в медиа-запросе называется breakpoint (контрольной точкой, или более просто классом устройства).

На схеме приведены основные контрольные точки, которые Bootstrap 4 имеет по умолчанию:

Это означает что до 576px макет сайта может отображаться одним образом, от 576px до 768px – другим образом и т.д. Таким образом, можно создать макет, который на каждом из этих участков может выглядеть по-разному.

Контрольные точки имеют обозначение. Первый breakpoint не имеет обозначения (), второй называется – , третий – , четвёртый – и пятый – . Эти обозначения необходимо запомнить, т.к. они используются в классах, которые мы будем добавлять к элементам. Эти обозначения в имени класса будут указывать на то с какой ширины viewport стили, определённые в нём, будут применяться к элементу.

Ширина viewport браузера Контрольная точка (название устройства)
>=0 без обозначения (xs)
>=576px sm
>=768px md
>=992px lg
>=1200px xl

При этом, контрольные точки задают только минимальную ширину. Т.е., например, если вы определили макет, используя в нём классы без обозначения контрольной точки () и с использованием , то он на будет иметь такую же структуру как на , а на и — как на .

Если вы знакомы с сеткой Bootstrap 3, то в ней количество контрольных точек равнялось четырём.

Summary

Here are the big ticket items you’ll want to be aware of when moving from v3 to v4.

Browser support

  • Dropped IE8, IE9, and iOS 6 support. v4 is now only IE10+ and iOS 7+. For sites needing either of those, use v3.
  • Added official support for Android v5.0 Lollipop’s Browser and WebView. Earlier versions of the Android Browser and WebView remain only unofficially supported.

Global changes

  • Flexbox is enabled by default. In general this means a move away from floats and more across our components.
  • Switched from Less to Sass for our source CSS files.
  • Switched from to as our primary CSS unit, though pixels are still used for media queries and grid behavior as device viewports are not affected by type size.
  • Global font-size increased from to .
  • Revamped grid tiers to add a fifth option (addressing smaller devices at and below) and removed the infix from those classes. Example: .
  • Replaced the separate optional theme with configurable options via SCSS variables (e.g., ).
  • Build system overhauled to use a series of npm scripts instead of Grunt. See for all scripts, or our project readme for local development needs.
  • Non-responsive usage of Bootstrap is no longer supported.
  • Dropped the online Customizer in favor of more extensive setup documentation and customized builds.
  • Added dozens of new utility classes for common CSS property-value pairs and margin/padding spacing shortcuts.

Grid system

  • Moved to flexbox.
    • Added support for flexbox in the grid mixins and predefined classes.
    • As part of flexbox, included support for vertical and horizontal alignment classes.
  • Updated grid class names and a new grid tier.
    • Added a new grid tier below for more granular control. We now have , , , , and . This also means every tier has been bumped up one level (so in v3 is now in v4).
    • grid classes have been modified to not require the infix to more accurately represent that they start applying styles at and not a set pixel value. Instead of , it’s now . All other grid tiers require the infix (e.g., ).
  • Updated grid sizes, mixins, and variables.
    • Grid gutters now have a Sass map so you can specify specific gutter widths at each breakpoint.
    • Updated grid mixins to utilize a prep mixin and a to set the and for individual column sizing.
    • Changed grid system media query breakpoints and container widths to account for new grid tier and ensure columns are evenly divisible by at their max width.
    • Grid breakpoints and container widths are now handled via Sass maps ( and ) instead of a handful of separate variables. These replace the variables entirely and allow you to fully customize the grid tiers.
    • Media queries have also changed. Instead of repeating our media query declarations with the same value each time, we now have . Now, instead of writing , you can write .

Components

  • Dropped panels, thumbnails, and wells for a new all-encompassing component, cards.
  • Dropped the Glyphicons icon font. If you need icons, some options are:
    • the upstream version of Glyphicons
    • Octicons
    • Font Awesome
    • See the Extend page for a list of alternatives. Have additional suggestions? Please open an issue or PR.
  • Dropped the Affix jQuery plugin.
    • We recommend using instead. for details and specific polyfill recommendations. One suggestion is to use an rule for implementing it (e.g., )/
    • If you were using Affix to apply additional, non- styles, the polyfills might not support your use case. One option for such uses is the third-party ScrollPos-Styler library.
  • Dropped the pager component as it was essentially slightly customized buttons.
  • Refactored nearly all components to use more un-nested class selectors instead of over-specific children selectors.

Examples

Alerts are available for any length of text, as well as an optional dismiss button. For proper styling, use one of the eight required contextual classes (e.g., ). For inline dismissal, use the .

A simple primary alert—check it out!

A simple secondary alert—check it out!

A simple success alert—check it out!

A simple danger alert—check it out!

A simple warning alert—check it out!

A simple info alert—check it out!

A simple light alert—check it out!

A simple dark alert—check it out!

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 class.

Link color

Use the utility class to quickly provide matching colored links within any alert.

A simple primary alert with . Give it a click if you like.

A simple secondary alert with . Give it a click if you like.

A simple success alert with . Give it a click if you like.

A simple danger alert with . Give it a click if you like.

A simple warning alert with . Give it a click if you like.

A simple info alert with . Give it a click if you like.

A simple light alert with . Give it a click if you like.

A simple dark alert with . Give it a click if you like.

Additional content

Alerts can also contain additional HTML elements like headings, paragraphs and dividers.

Well done!

Aww yeah, you successfully read this important alert message. This example text is going to run a bit longer so that you can see how spacing within an alert works with this kind of content.

Whenever you need to, be sure to use margin utilities to keep things nice and tidy.

Dismissing

Using the alert JavaScript plugin, it’s possible to dismiss any alert inline. Here’s how:

  • Be sure you’ve loaded the alert plugin, or the compiled Bootstrap JavaScript.
  • If you’re building our JavaScript from source, it . The compiled version includes this.
  • Add a dismiss button and the class, which adds extra padding to the right of the alert and positions the button.
  • On the dismiss button, add the attribute, which triggers the JavaScript functionality. Be sure to use the element with it for proper behavior across all devices.
  • To animate alerts when dismissing them, be sure to add the and classes.

You can see this in action with a live demo:

Holy guacamole! You should check in on some of those fields below. ×

Beta 2 changes

While in beta, we aim to have no breaking changes. However, things don’t always go as planned. Below are the breaking changes to bear in mind when moving from Beta 1 to Beta 2.

Breaking

  • Removed variable and its usage on . We use a color contrast function to pick a based on the , so the variable is unnecessary.
  • Renamed function to to avoid breaking conflict with the CSS native filter.
  • Renamed , , and to and , matching our color schemes used elsewhere.
  • Responsive tables now generate classes for each grid breakpoint. This breaks from Beta 1 in that the you’ve been using is more like . You may now use or as needed.
  • Dropped Bower support as the package manager has been deprecated for alternatives (e.g., Yarn or npm). See bower/bower#2298 for details.
  • Bootstrap still requires jQuery 1.9.1 or higher, but you’re advised to use version 3.x since v3.x’s supported browsers are the ones Bootstrap supports plus v3.x has some security fixes.
  • Removed the unused class. If you did make use of this class, it was duplicate of the class that vertically centered a with it’s associated input in horizontal form layouts.
  • Changed the from a mixin that included the property to a function that returns a value, allowing you to use it for any CSS property. For example, instead of , you’d write .

Highlights

Introduced new pointer-events usage on modals. The outer .modal-dialog passes through events with pointer-events: none for custom click handling (making it possible to just listen on the .modal-backdrop for any clicks), and then counteracts it for the actual .modal-content with pointer-events: auto.


С этим читают