My first bootstrap page

Sass options

Customize Bootstrap 4 with our built-in custom variables file and easily toggle global CSS preferences with new Sass variables. Override a variable’s value and recompile with as needed.

You can find and customize these variables for key global options in our file.

Variable Values Description
(default), or any value > 0 Specifies the default spacer value to programmatically generate our spacer utilities.
(default) or Enables predefined styles on various components.
or (default) Enables predefined styles on various components.
or (default) Enables predefined gradients via styles on various components.
(default) or Enables predefined s on various components.
or (default) Deprecated
(default) or Enables the generation of CSS classes for the grid system (e.g., , , , etc.).
(default) or Enables pseudo element caret on .
(default) or Enables styles for optimizing printing.

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.

Global settings

Bootstrap sets basic global display, typography, and link styles. When more control is needed, check out the textual utility classes.

  • Use a that selects the best for each OS and device.
  • For a more inclusive and accessible type scale, we assume the browser default root (typically 16px) so visitors can customize their browser defaults as needed.
  • Use the , , and attributes as our typographic base applied to the .
  • Set the global link color via and apply link underlines only on .
  • Use to set a on the ( by default).

These styles can be found within , and the global variables are defined in . Make sure to set in .

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 .

Disabled forms

Add the boolean attribute on an input to prevent user interactions and make it appear lighter.

Add the attribute to a to disable all the controls within.

Caveat with anchors

By default, browsers will treat all native form controls (, and elements) inside a as disabled, preventing both keyboard and mouse interactions on them. However, if your form also includes elements, these will only be given a style of . As noted in the section about (and specifically in the sub-section for anchor elements), this CSS property is not yet standardized and isn’t fully supported in Opera 18 and below, or in Internet Explorer 10, and won’t prevent keyboard users from being able to focus or activate these links. So to be safe, use custom JavaScript to disable such links.

While Bootstrap will apply these styles in all browsers, Internet Explorer 11 and below don’t fully support the attribute on a . Use custom JavaScript to disable the fieldset in these browsers.

Contextual classes

Use contextual classes to color table rows or individual cells.

Class Heading Heading
Active Cell Cell
Default Cell Cell
Primary Cell Cell
Secondary Cell Cell
Success Cell Cell
Danger Cell Cell
Warning Cell Cell
Info Cell Cell
Light Cell Cell
Dark Cell Cell

Regular table background variants are not available with the dark table, however, you may use text or background utilities to achieve similar styles.

# Heading Heading
1 Cell Cell
2 Cell Cell
3 Cell Cell
4 Cell Cell
5 Cell Cell
6 Cell Cell
7 Cell Cell
8 Cell Cell
9 Cell Cell
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.

Create responsive tables by wrapping any with , making the table scroll horizontally at each breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.

Note that since browsers do not currently support , we work around the limitations of and viewports with fractional widths (which can occur under certain conditions on high-dpi devices, for instance) by using values with higher precision for these comparisons.

Чекбоксы и радио

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

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

По умолчанию (наборный)

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

Example

Badges scale to match the size of the immediate parent element by using relative font sizing and units.

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New
Example heading New

Badges can be used as part of links or buttons to provide a counter.

Notifications 4

Note that depending on how they are used, badges may be confusing for users of screen readers and similar assistive technologies. While the styling of badges provides a visual cue as to their purpose, these users will simply be presented with the content of the badge. Depending on the specific situation, these badges may seem like random additional words or numbers at the end of a sentence, link, or button.

Unless the context is clear (as with the “Notifications” example, where it is understood that the “4” is the number of notifications), consider including additional context with a visually hidden piece of additional text.

Profile 9
unread messages

Contextual variations

Add any of the below mentioned modifier classes to change the appearance of a badge.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

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.

Pill badges

Use the modifier class to make badges more rounded (with a larger and additional horizontal ). Useful if you miss the badges from v3.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

Using the contextual classes on an element quickly provide actionable badges with hover and focus states.

Sass mixins

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

Classes

Aside from our Reboot, a cross-browser normalization stylesheet, all our styles aim to use classes as selectors. This means steering clear of type selectors (e.g., ) and extraneous parent classes (e.g., ) that make styles too specific to easily override.

As such, components should be built with a base class that houses common, not-to-be overridden property-value pairs. For example, and . We use for all the common styles like , , and . We then use modifiers like to add the color, background-color, border-color, etc.

Modifier classes should only be used when there are multiple properties or values to be changed across multiple variants. Modifiers are not always necessary, so be sure you’re actually saving lines of code and preventing unnecessary overrides when creating them. Good examples of modifiers are our theme color classes and size variants.

Examples

Wrap the dropdown’s toggle (your button or link) and the dropdown menu within , or another element that declares . Dropdowns can be triggered from or elements to better fit your potential needs.

Single button

Any single can be turned into a dropdown toggle with some markup changes. Here’s how you can put them to work with either elements:

Dropdown button

And with elements:

The best part is you can do this with any button variant, too:

Primary

Secondary

Success

Info

Warning

Danger

Split button

Similarly, create split button dropdowns with virtually the same markup as single button dropdowns, but with the addition of for proper spacing around the dropdown caret.

We use this extra class to reduce the horizontal on either side of the caret by 25% and remove the that’s added for regular button dropdowns. Those extra changes keep the caret centered in the split button and provide a more appropriately sized hit area next to the main button.

Primary

Toggle Dropdown

Secondary

Toggle Dropdown

Success

Toggle Dropdown

Info

Toggle Dropdown

Warning

Toggle Dropdown

Danger

Toggle Dropdown

Примеры

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

Well done! You successfully read this important alert message.

Heads up! This alert needs your attention, but it’s not super important.

Warning! Better check yourself, you’re not looking too good.

Oh snap! Change a few things up and try submitting again.

Передать смысл для ассистивных технологий

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

Цвет ссылок

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

Well done! You successfully read .

Heads up! This , but it’s not super important.

Warning! Better check yourself, you’re .

Oh snap! and try submitting again.

Дополнительный контент

Уведомления также могут содержать дополнительные элементы HTML, как заголовки и абзацы.

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.

Отклоняющие

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

  • Убедитесь, что вы загрузили плагин оповещения, или скомпилированный Bootstrap JavaScript.
  • Добавить кнопки «закрыть» и класс, который добавляет дополнительный внутренний отступ правое предупреждения и позиции #1 кнопка#.
  • На кнопку закрыть, добавить атрибут, который инициирует JavaScript функциональности. Обязательно используйте элемент для правильного поведения во всех устройствах.
  • Чтобы анимировать предупреждения при увольнении их, не забудьте добавить и классы.

Вы можете увидеть это в действии с демо:

×

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

File Input

Bootstrap File Input

Bootstrap File Input is a field which the user can use to upload one or more files (photos, documents or any other
file type) from local storage.

Standard file inputs usually leave a lot to be desired in terms of design, but MDB takes care of that by enhancing
them with Material Design best practices.

Some of the most common use examples are:

  • CSV upload to CRM system
  • Avatar picture upload
  • Simple GIF upload

Below you can see a number of Bootstrap file inputs created with Material Design for Bootstrap.

Note info: The recommended plugin to animate default file input:
bs-custom-file-input, that’s what we are using
currently in our packages and you don’t have to add by yourself.

Note info: If you need more advanced functionalities, have a look at our
Drag and drop file upload plugin.

Examples

Basic

To encourage extensible and predictable toasts, we recommend a header and body. Toast headers use , allowing easy alignment of content thanks to our margin and flexbox utilities.

Toasts are as flexible as you need and have very little required markup. At a minimum, we require a single element to contain your “toasted” content and strongly encourage a dismiss button.

Bootstrap
11 mins ago

×

Hello, world! This is a toast message.

Translucent

Toasts are slightly translucent, too, so they blend over whatever they might appear over. For browsers that support the CSS property, we’ll also attempt to blur the elements under a toast.

Bootstrap
11 mins ago

×

Hello, world! This is a toast message.

Stacking

When you have multiple toasts, we default to vertiaclly stacking them in a readable manner.

Bootstrap
just now

×

See? Just like this.

Bootstrap
2 seconds ago

×

Heads up, toasts will stack automatically

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.

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 sets the width 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 ).

Модули, navbars, и виртуальные клавиатуры

Переполнение и прокрутка

Поддержка на элемент весьма ограничен в iOS и Android. С этой целью, когда вы прокрутите мимо верхней или нижней части модального в любом из браузеров этих устройств, в контент начнет прокручиваться. Смотрите Хром ошибка № 175502 (исправлено в Chrome и V40) и В WebKit ошибка #153852.

текстовых полей iOS и прокрутки

Начиная с iOS 9.3, в то время как модальные открыт, если начальное касание прокрутки жест в пределах границы текста или В содержание под модальным будет прокручиваться вместо модальных себя. Смотрите В WebKit ошибка № 153856.

Виртуальная клавиатура

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

Bootstrap не обрабатывает такие ошибки, так что вам нужно самим это решить.

Меню Навигации

Элемент не используется на iOS в навигации из-за сложности с z-index. Таким образом, чтобы закрыть выпадающие меню, необходимо просто нажать элемент выпадающего (или ).

Responsive classes

Bootstrap’s grid includes five 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 before becoming horizontal with 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-12 .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

Responsive

Bootstrap’s responsive styles are built to be responsive, an approach that’s often referred to as mobile-first. We use this term in our docs and largely agree with it, but at times it can be too broad. While not every component must be entirely responsive in Bootstrap, this responsive approach is about reducing CSS overrides by pushing you to add styles as the viewport becomes larger.

Across Bootstrap, you’ll see this most clearly in our media queries. In most cases, we use queries that begin to apply at a specific breakpoint and carry up through the higher breakpoints. For example, a applies from to infinity. On the other hand, a applies from the medium breakpoint and up.

At times we’ll use when a component’s inherent complexity requires it. At times, these overrides are functionally and mentally clearer to implement and support than rewriting core functionality from our components. We strive to limit this approach, but will use it from time to time.

JavaScript поведение

Триггеры

Включить увольнения сигнал через JavaScript:

Или с атрибутами на кнопку в предупреждение, как показано выше:

Обратите внимание, что закрытие предупреждения будет удален из DOM

Методы

Способ Описание
Делает оповещение, прослушивание события щелчка на дочерние элементы, которые имеют атрибут . (Не требуется при использовании данных API для автоматической инициализации.)
Закрывается предупреждение, удалив его из DOM. Если и классы присутствуют на элемент, предупреждение исчезнет, прежде чем он будет удален.

События

Bootstrap плагин оповещения предоставляет несколько событий для навески функционал оповещения.

Событие Описание
Это событие возникает сразу же, когда вызывается способ экземпляра.
Это событие запускается, когда сигнал был закрыт (будем ждать CSS переходы для завершения).

Неактивное состояние

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

Добавить атрибута на чтобы отключить все элементы управления внутри.

Предостережение о ссылке функциональности

По умолчанию браузеры будут лечить все родные элементы управления (, и элементы) внутри как отключить, предотвращение клавиатуры и действия мыши на них. Однако, если ваша форма также содержит элемент, только с учетом стиля . Как отмечалось в разделе О (и в частности, в подразделе для якорных элементов), этот CSS собственность еще не стандартизировано и не полностью поддерживаются в Opera 18 и ниже, или в Internet Explorer 11, и не допустить клавиатуры пользователям возможность сосредоточиться или активировать эти ссылки. Поэтому, чтобы быть в безопасности, используйте настраиваемые JavaScript отключить такие ссылки.

Кросс-браузерная совместимость

При Bootstrap будут применять эти стили во всех браузерах, Internet Explorer 11 и ниже не полностью поддерживает атрибут на . Используйте настраиваемые JavaScript отключить полей в этих браузерах.

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

Пользовательские компоненты

Одностраничный шаблон для построения простых и красивых домашних страниц.

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

Простой блог в две колонки с пользовательской навигацией, заголовком, и видом.

Базовая структура для администратора приборная панель с фиксированным боковым меню и панели навигации.

Шаблон пользовательской формы настроен для простого входа на сайт.

Создание компонованого нав. меню с выровненными ссылками

Внимание!

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

Contextual classes

Use contextual classes to style list items with a stateful background and color.

  • Dapibus ac facilisis in
  • This is a primary list group item
  • This is a secondary list group item
  • This is a success list group item
  • This is a danger list group item
  • This is a warning list group item
  • This is a info list group item
  • This is a light list group item
  • This is a dark list group item

Contextual classes also work with . Note the addition of the hover styles here not present in the previous example. Also supported is the state; apply it to indicate an active selection on a contextual list group item.

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.

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

Ссылка на основную публикацию