Группа полей ввода
Содержание:
- Checkboxes and Radios
- Custom Select Menu Size
- Форма в одну строку
- Form Control States
- Supported Form Controls
- Static Control
- Быстрый старт
- Строка формы
- Block buttons
- Disabled state
- Responsive classes
- Static Controls
- Горизонтальная форма
- Validation and Errors
- Form text
- Disabled forms
- Bootstrap Checkboxes
- Forms
- Variants
- Other Tips and Edge Cases
- Флажки и переключатели
- Accessibility
Checkboxes and Radios
Checkboxes and radios should be placed inside of a to render
properly. The following example ensures that the entire form group will display
an error if an associated validations fails:
<%= f.form_group :skill_level, label: { text: "Skill" }, help: "Optional Help Text" do %> <%= f.radio_button :skill_level, 0, label: "Novice", checked: true %> <%= f.radio_button :skill_level, 1, label: "Intermediate" %> <%= f.radio_button :skill_level, 2, label: "Advanced" %> <% end %> <%= f.form_group :terms do %> <%= f.check_box :terms, label: "I agree to the Terms of Service" %> <% end %>
You can also create a checkbox using a block:
<%= f.form_group :terms, label: { text: "Optional Label" } do %> <%= f.check_box :terms do %> You need to check this box to accept our terms of service and privacy policy <% end %> <% end %>
To display checkboxes and radios inline, pass the option:
<%= f.form_group :skill_level, label: { text: "Skill" } do %> <%= f.radio_button :skill_level, 0, label: "Novice", inline: true %> <%= f.radio_button :skill_level, 1, label: "Intermediate", inline: true %> <%= f.radio_button :skill_level, 2, label: "Advanced", inline: true %> <% end %>
Check boxes and radio buttons are wrapped in a . You can add classes to this with the option:
<%= f.radio_button :skill_level, 0, label: "Novice", inline: true, wrapper_class: "w-auto" %>
To render checkboxes as switches with Bootstrap 4.2+, use :
<%= f.check_box :remember_me, custom: :switch %>
Collections
also provides helpers that automatically create the
and the s or es for you:
<%= f.collection_radio_buttons :skill_level, Skill.all, :id, :name %> <%= f.collection_check_boxes :skills, Skill.all, :id, :name %>
NOTE: These helpers do not currently support a block, unlike their equivalent Rails helpers. See issue #477. If you need to use the block syntax, use or for now.
Collection methods accept these options:
- : Customize the ‘s label
- : Pass true to hide the ‘s label
- : Add a help span to the
- Other options will be forwarded to the / method
Custom Select Menu Size
Use the class to create a small select menu and the class for a large one:
Small Custom Select MenuVolvoFiatAudiDefault Custom Select MenuVolvoFiatAudiLarge Custom Select MenuVolvoFiatAudi
Example
<form> <!— Small —> <select name=»cars» class=»custom-select-sm»>
<option selected>Small Custom Select Menu</option> <option
value=»volvo»>Volvo</option> <option value=»fiat»>Fiat</option>
<option value=»audi»>Audi</option> </select> <!— Large —> <select name=»cars» class=»custom-select-lg»>
<option selected>Large Custom Select Menu</option> <option
value=»volvo»>Volvo</option> <option value=»fiat»>Fiat</option>
<option value=»audi»>Audi</option> </select></form>
Форма в одну строку
Используйте класс .form-inline, чтобы элементы формы отображались как строчно-блочные и выравнивались по левому краю. Используйте вспомогательные класса (например, mr-sm-2), чтобы добавить пространство между элементами.
Обратите внимание, всё это применимо только тогда, когда область просмотра имеет ширину не меньше 576 пикселей.
Имя
Фамилия
Отправить
<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css»>
<form class=»form-inline»>
<label class=»mr-sm-2 mb-0″ for=»first_name»>Имя</label>
<input type=»text» class=»form-control mr-sm-2 mb-2 mb-sm-0″ id=»first_name» name=»first_name»>
<label class=»mr-sm-2 mb-0″ for=»last_name»>Фамилия</label>
<input type=»text» class=»form-control mr-sm-2 mb-2 mb-sm-0″ id=»last_name» name=»last_name»>
<button type=»submit» class=»btn btn-primary mt-2 mt-sm-0″>Отправить</button>
</form>
Form Control States
In addition to the :focus (i.e., a user clicks into the input or tabs onto it) state, Bootstrap offers styling for disabled inputs and classes for form validation.
Disabled lnputs
If you need to disable an input, simply adding the disabled attribute will not only disable it; it will also change the styling and the mouse cursor when the cursor hovers over the element.
Validation States
Bootstrap includes validation styles for errors, warnings, and success messages. To use, simply add the appropriate class (.has-warning, .has-error, or .has-success) to the parent element.
The following example demonstrates all the form control states −
<form class = "form-horizontal" role = "form"> <div class = "form-group"> <label class = "col-sm-2 control-label">Focused</label> <div class = "col-sm-10"> <input class = "form-control" id = "focusedInput" type = "text" value = "This is focused..."> </div> </div> <div class = "form-group"> <label for = "inputPassword" class = "col-sm-2 control-label"> Disabled </label> <div class = "col-sm-10"> <input class = "form-control" id = "disabledInput" type = "text" placeholder = "Disabled input here..." disabled> </div> </div> <fieldset disabled> <div class = "form-group"> <label for = "disabledTextInput" class = "col-sm-2 control-label"> Disabled input (Fieldset disabled) </label> <div class = "col-sm-10"> <input type = "text" id = "disabledTextInput" class = "form-control" placeholder = "Disabled input"> </div> </div> <div class = "form-group"> <label for = "disabledSelect" class = "col-sm-2 control-label"> Disabled select menu (Fieldset disabled) </label> <div class = "col-sm-10"> <select id = "disabledSelect" class = "form-control"> <option>Disabled select</option> </select> </div> </div> </fieldset> <div class = "form-group has-success"> <label class = "col-sm-2 control-label" for = "inputSuccess"> Input with success </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputSuccess"> </div> </div> <div class = "form-group has-warning"> <label class = "col-sm-2 control-label" for = "inputWarning"> Input with warning </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputWarning"> </div> </div> <div class = "form-group has-error"> <label class = "col-sm-2 control-label" for = "inputError"> Input with error </label> <div class = "col-sm-10"> <input type = "text" class = "form-control" id = "inputError"> </div> </div> </form>
Supported Form Controls
Bootstrap natively supports the most common form controls mainly input, textarea, checkbox, radio, and select.
Inputs
<form role = "form"> <div class = "form-group"> <label for = "name">Label</label> <input type = "text" class = "form-control" placeholder = "Text input"> </div> </form>
Textarea
The textarea is used when you need multiple lines of input. Change rows attribute as necessary (fewer rows = smaller box, more rows = bigger box).
<form role = "form"> <div class = "form-group"> <label for = "name">Text Area</label> <textarea class = "form-control" rows = "3"></textarea> </div> </form>
CheckBoxes and Radio Buttons
Checkboxes and radio buttons are great when you want users to choose from a list of preset options.
-
When building a form, use checkbox if you want the user to select any number of options from a list. Use radio if you want to limit the user to just one selection.
-
Use .checkbox-inline or .radio-inline class to a series of checkboxes or radios for controls appear on the same line.
The following example demonstrates both (default and inline) types −
<label for = "name">Example of Default Checkbox and radio button </label> <div class = "checkbox"> <label> <input type = "checkbox" value = "">Option 1 </label> </div> <div class = "checkbox"> <label> <input type = "checkbox" value = "">Option 2 </label> </div> <div class = "radio"> <label> <input type = "radio" name = "optionsRadios" id = "optionsRadios1" value = "option1" checked> Option 1 </label> </div> <div class = "radio"> <label> <input type = "radio" name = "optionsRadios" id = "optionsRadios2" value = "option2"> Option 2 - selecting it will deselect option 1 </label> </div> <label for = "name">Example of Inline Checkbox and radio button </label> <div> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox1" value = "option1"> Option 1 </label> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Option 2 </label> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox3" value = "option3"> Option 3 </label> <label class = "checkbox-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios3" value = "option1" checked> Option 1 </label> <label class = "checkbox-inline"> <input type = "radio" name = "optionsRadiosinline" id = "optionsRadios4" value = "option2"> Option 2 </label> </div>
Selects
A select is used when you want to allow the user to pick from multiple options, but by default it only allows one.
-
Use <select> for list options with which the user is familiar, such as states or numbers.
-
Use multiple = «multiple» to allow the users to select more than one option.
The following example demonstrates both (select and multiple) types −
<form role = "form"> <div class = "form-group"> <label for = "name">Select list</label> <select class = "form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <label for = "name">Mutiple Select list</label> <select multiple class = "form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> </form>
Static Control
Use the class .form-control-static on a <p>, when you need to place plain text next to a form label within a horizontal form.
<form class = "form-horizontal" role = "form"> <div class = "form-group"> <label class = "col-sm-2 control-label">Email</label> <div class = "col-sm-10"> <p class = "form-control-static">email@example.com</p> </div> </div> <div class = "form-group"> <label for = "inputPassword" class = "col-sm-2 control-label">Password</label> <div class = "col-sm-10"> <input type = "password" class = "form-control" id = "inputPassword" placeholder = "Password"> </div> </div> </form>
Быстрый старт
Хотите быстро добавить Bootstrap в свой проект? Используйте jsDelivr, бесплатный CDN с открытым исходным кодом. Используете менеджер пакетов или вам нужно скачать исходные файлы? Перейдите на страницу загрузок.
Скрипты
Многие из наших компонентов требуют использования JavaScript для работы. В частности, для них требуются наши собственные плагины JavaScript и Popper. Поместите один из следующих в конце Ваших страниц, прямо перед закрывающим тегом , чтобы включить их.
Связка
Включите каждый плагин Bootstrap JavaScript и зависимости в один из двух наших пакетов. Наши и включают Popper. Для получения дополнительной информации о том, что входит в Bootstrap, см. наш раздел .
Раздельно
Если Вы решите использовать отдельное решение для сценариев, сначала должен быть Popper.js (если Вы используете всплывающие подсказки или всплывающие окна), а затем наши плагины JavaScript.
Компоненты
Интересно, какие компоненты явно требуют нашего JavaScript и Popper? Кликните на ссылку “Показать компоненты” ниже. Если Вы совсем не уверены в общей структуре страницы, продолжайте читать, чтобы найти образец шаблона страницы.
Показать компоненты, требующие JavaScript
- Alerts (Уведомления) для отклонения
- Buttons (Кнопки) для переключения состояний и функционала флажка/радио
- Carousel (Карусель) для любого поведения слайдов, элементов управления и индикаторов
- Collapse (Сворачиваемое) для переключения видимости содержимого
- Dropdowns (Выпадающие списки) для отображения и позиционирования (также требуется Popper)
- Modals (Модальные окна) для отображения, позиционирования и прокрутки
- Navbar (Панель навигации) для расширения нашего плагина Сворачиваемое для реализации адаптивного поведения
- Offcanvases (Внехолста) для отображения, позиционирования и поведения прокрутки
- Toasts (Тосты) для показа и отклонения
- Tooltips (Всплывающие подсказки) и popovers (всплывающие окна) для отображения и позиционирования (также требуется Popper)
- Scrollspy (Отслеживание прокрутки) для поведения прокрутки и обновлений навигации
Строка формы
Вы можете заменить .row на .form-row для более компактной компоновки.
<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css»>
<p><code>.row</code>:</p>
<form>
<div class=»row»>
<div class=»col»>
<input type=»text» class=»form-control» placeholder=»Имя»>
</div>
<div class=»col»>
<input type=»text» class=»form-control» placeholder=»Фамилия»>
</div>
</div>
</form>
<p class=»mt-5″><code>.form-row</code>:</p>
<form>
<div class=»form-row»>
<div class=»col»>
<input type=»text» class=»form-control» placeholder=»Имя»>
</div>
<div class=»col»>
<input type=»text» class=»form-control» placeholder=»Фамилия»>
</div>
</div>
</form>
Create responsive stacks of full-width, “block buttons” like those in Bootstrap 4 with a mix of our display and gap utilities. By using utilities instead of button specific classes, we have much greater control over spacing, alignment, and responsive behaviors.
Button
Button
Here we create a responsive variation, starting with vertically stacked buttons until the breakpoint, where replaces the class, thus nullifying the utility. Resize your browser to see them change.
Button
Button
You can adjust the width of your block buttons with grid column width classes. For example, for a half-width “block button”, use . Center it horizontally with , too.
Button
Button
Additional utilities can be used to adjust the alignment of buttons when horizontal. Here we’ve taken our previous responsive example and added some flex utilities and a margin utility on the button to right align the buttons when they’re no longer stacked.
Button
Button
Disabled state
Make buttons look inactive by adding the boolean attribute to any element. Disabled buttons have applied to, preventing hover and active states from triggering.
Primary button
Button
Disabled buttons using the element behave a bit different:
- s don’t support the attribute, so you must add the class to make it visually appear disabled.
- Some future-friendly styles are included to disable all on anchor buttons.
- Disabled buttons using should include the attribute to indicate the state of the element to assistive technologies.
- Disabled buttons using should not include the attribute.
Primary link
Link
Link functionality caveat
To cover cases where you have to keep the attribute on a disabled link, the class uses to try to disable the link functionality of s. Note that this CSS property is not yet standardized for HTML, but all modern browsers support it. In addition, even in browsers that do support , keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, in addition to , also include a attribute on these links to prevent them from receiving keyboard focus, and use custom JavaScript to disable their functionality altogether.
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, :
Static Controls
You can create a static control like this:
<%= f.static_control :email %>
Here’s the output for a horizontal layout:
<div class="form-group"> <label class="col-sm-2 form-control-label" for="user_email">Email</label> <div class="col-sm-10"> <input class="form-control-plaintext" id="user_email" name="user" readonly="readonly" type="text" value="test@email.com"/> </div> </div>
You can also create a static control that isn’t based on a model attribute:
<%= f.static_control :field_name, label: "Custom Static Control", value: "Content Here" %>
may be any name that isn’t already used in the form. Note that you may get «unpermitted parameter» messages in your log file with this approach.
You can also create the static control the following way, if you don’t need to get the value of the static control as a parameter when the form is submitted:
<%= f.static_control label: "Custom Static Control", value: "Content Here", name: nil %>
(If you neither provide a field name nor , the Rails code that submits the form will give a JavaScript error.)
Prior to version 4 of , you could pass a block to the method.
The value of the block would be used for the content of the static «control».
Bootstrap 4 actually creates and styles a disabled input field for static controls, so the value of the control has to be specified by the option.
Passing a block to no longer has any effect.
Горизонтальная форма
Вы можете использовать классы сетки Bootstrap для создания горизонтальных форм. Просто укажите, сколько колонок должен занимать каждый элемент. В частности, добавьте класс .row к .form-group и класс .col-*-* или .col-* для каждой колонки.
Вы также должны добавить класс .col-form-label к элементу <label>, чтобы метка относительно текстовых полей расположилась по центру вертикали.
<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css»>
<div class=»container»>
<form>
<div class=»form-group row»>
<label for=»first_name» class=»col-xs-3 col-form-label mr-2″>Имя</label>
<div class=»col-xs-9″>
<input type=»text» class=»form-control» id=»first_name» name=»first_name»>
</div>
</div>
<div class=»form-group row»>
<label for=»last_name» class=»col-xs-3 col-form-label mr-2″>Фамилия</label>
<div class=»col-xs-9″>
<input type=»text» class=»form-control» id=»last_name» name=»last_name»>
</div>
</div>
<div class=»form-group row»>
<div class=»offset-xs-3 col-xs-9″>
<button type=»submit» class=»btn btn-primary»>Отправить</button>
</div>
</div>
</form>
</div>
Bootstrap 4 против Bootstrap 3
Когда речь идёт о горизонтальных формах, имеются некоторые незначительные различия между Bootstrap 4 и Bootstrap 3.
Сетки
При использовании сеток для макета формы, Bootstrap 4 требует класс .row. Этот класс не является обязательным для форм Bootstrap 3 (хотя по прежнему обязателен для сеток Bootstrap 3).
Метки
Bootstrap 4 использует .col-form-label в сетке макета формы, тогда как Bootstrap 3 использует .control-label
Обратите внимание, что Bootstrap 4 изначально использовал .form-control-label, но впоследствии заменил его на .col-form-label.
Класс .form-horizontal
Bootstrap 3 требует класс .form-horizontal, тогда как Bootstrap 4 нет.
Validation and Errors
Rails normally wraps fields with validation errors in a , but this behaviour isn’t consistent with Bootstrap 4 styling. By default, generations in-line errors which appear below the field. But it can also generate errors on the label, or not display any errors, leaving it up to you.
Inline Errors
By default, fields that have validation errors will be outlined in red and the
error will be displayed below the field. Here’s an example:
<div class="form-group"> <label class="form-control-label" for="user_email">Email</label> <input class="form-control is-invalid" id="user_email" name="user" type="email" value=""> <small class="invalid-feedback">can't be blank</small> </div>
You can turn off inline errors for the entire form like this:
<%= bootstrap_form_for(@user, inline_errors: false) do |f| %> ... <% end %>
Label Errors
You can also display validation errors in the field’s label; just turn
on the option. Here’s an example:
<%= bootstrap_form_for(@user, label_errors: true) do |f| %> ... <% end %>
By default, turning on will also turn off
. If you want both turned on, you can do that too:
<%= bootstrap_form_for(@user, label_errors: true, inline_errors: true) do |f| %> ... <% end %>
Alert Messages
To display an error message with an error summary, you can use the
helper. This won’t output anything unless a model validation
has failed.
<%= f.alert_message "Please fix the errors below." %>
Which outputs:
<div class="alert alert-danger"> <p>Please fix the errors below.</p> <ul class="rails-bootstrap-forms-error-summary"> <li>Email can't be blank</li> </ul> </div>
You can turn off the error summary like this:
<%= f.alert_message "Please fix the errors below.", error_summary: false %>
To output a simple unordered list of errors, use the helper.
<%= f.error_summary %>
Which outputs:
<ul class="rails-bootstrap-forms-error-summary"> <li>Email can't be blank</li> </ul>
Errors On
If you want to display a custom inline error for a specific attribute not
represented by a form field, use the helper.
<%= f.errors_on :tasks %>
Which outputs:
<div class="alert alert-danger">Tasks can't be blank.</div>
You can hide the attribute name like this:
<%= f.errors_on :tasks, hide_attribute_name: true %>
Which outputs:
<div class="alert alert-danger">can't be blank.</div>
Form text
Block-level or inline-level form text can be created using .
Associating form text with form controls
Form text should be explicitly associated with the form control it relates to using the attribute. This will ensure that assistive technologies—such as screen readers—will announce this form text when the user focuses or enters the control.
Form text below inputs can be styled with . If a block-level element will be used, a top margin is added for easy spacing from the inputs above.
Inline text can use any typical inline HTML element (be it a , , or something else) with nothing more than the class.
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. Browsers 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 custom button-like elements such as , these will only be given a style of , meaning they are still focusable and operable using the keyboard. In this case, you must manually modify these controls by adding to prevent them from receiving focus and to signal their state to assistive technologies.
Bootstrap Checkboxes
Checkboxes are used if you want the user to select any number of options from
a list of preset options.
The following example contains three checkboxes. The last option is disabled:
Example
<div class=»form-check»> <label class=»form-check-label»>
<input type=»checkbox» class=»form-check-input» value=»»>Option 1
</label></div><div class=»form-check»> <label
class=»form-check-label»> <input type=»checkbox»
class=»form-check-input» value=»»>Option 2 </label></div>
<div class=»form-check»> <label class=»form-check-label»>
<input type=»checkbox» class=»form-check-input» value=»» disabled>Option 3
</label></div>
Example explained
Use a wrapper element with to ensure proper margins for labels and checkboxes.
Add the class to label elements, and to style checkboxes properly inside the container.
Forms
Every group of form fields should reside in a element. Bootstrap provides no default styling for the element, but there are some powerful browser features that are provided by default.
- New to browser forms? Consider reviewing the MDN form docs for an overview and complete list of available attributes.
- s within a default to , so strive to be specific and always include a .
- You can disable every form element within a form with the attribute on the .
Since Bootstrap applies and to almost all our form controls, forms will by default stack vertically. Additional classes can be used to vary this layout on a per-form basis.
Variants
Use contextual classes to color tables, table rows or individual cells.
Class | Heading | Heading |
---|---|---|
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 |
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.
Other Tips and Edge Cases
By their very nature, forms are extremely diverse. It would be extremely difficult to provide a gem that could handle every need. Here are some tips for handling edge cases.
Empty But Visible Labels
Some third party plug-ins require an empty but visible label on an input control. The option generates a label that won’t appear on the screen, but it’s considered invisible and therefore doesn’t work with such a plug-in. An empty label (e.g. ) causes the underlying Rails helper to generate a label based on the field’s attribute’s name.
The solution is to use a zero-width character for the label, or some other «empty» HTML. For example:
label: "​".html_safe
or
label: "<span></span>".html_safe
Флажки и переключатели
Bootstrap 4 предоставляет классы .form-check, .form-check-label, .form-check-input и .form-check-inline для отображения флажков и переключателей.
Чтобы отобразить флажки или переключатели друг под другом, вложите каждый из них в элемент <div> с классом .form-check. Кроме того, добавьте .form-check-label к элементу <label> и .form-check-input к элементу <input>.
В одну строку
В Bootstrap 4 флажки и переключатели по умолчанию располагаются друг под другом. Вы можете отобразить их в одну строку, добавив .form-check-inline к внешнему <div>. Оставьте .form-check-input в элементе <input>.
<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css»>
<!— Флажки —>
<div class=»form-check form-check-inline»>
<input class=»form-check-input» type=»checkbox» id=»inlineCheckbox1″ value=»1″>
<label class=»form-check-label»>1</label>
</div>
<div class=»form-check form-check-inline»>
<input class=»form-check-input» type=»checkbox» id=»inlineCheckbox2″ value=»2″>
<label class=»form-check-label»>2</label>
</div>
<div class=»form-check form-check-inline»>
<input class=»form-check-input» type=»checkbox» id=»inlineCheckbox3″ value=»3″>
<label class=»form-check-label»>3</label>
</div>
<!— Переключатели —>
<div class=»form-check form-check-inline»>
<input class=»form-check-input» type=»radio» name=»inlineRadioOptions» id=»inlineRadio1″ value=»1″>
<label class=»form-check-label»>1</label>
</div>
<div class=»form-check form-check-inline»>
<input class=»form-check-input» type=»radio» name=»inlineRadioOptions» id=»inlineRadio2″ value=»2″>
<label class=»form-check-label»>2</label>
</div>
<div class=»form-check form-check-inline»>
<input class=»form-check-input» type=»radio» name=»inlineRadioOptions» id=»inlineRadio3″ value=»3″>
<label class=»form-check-label»>3</label>
</div>
</div>
Bootstrap 4 против Bootstrap 3
Bootstrap 3 для отображения флажков и переключателей использует .radio, .radio-inline, .checkbox или .checkbox-inline. Bootstrap 4 использует .form-check, .form-check-label, .form-check-input и .form-check-inline.
Accessibility
Ensure that all form controls have an appropriate accessible name so that their purpose can be conveyed to users of assistive technologies. The simplest way to achieve this is to use a element, or—in the case of buttons—to include sufficiently descriptive text as part of the content.
For situations where it’s not possible to include a visible or appropriate text content, there are alternative ways of still providing an accessible name, such as:
- elements hidden using the class
- Pointing to an existing element that can act as a label using
- Providing a attribute
- Explicitly setting the accessible name on an element using
If none of these are present, assistive technologies may resort to using the attribute as a fallback for the accessible name on and elements. The examples in this section provide a few suggested, case-specific approaches.
While using visually hidden content (, , and even content, which disappears once a form field has content) will benefit assistive technology users, a lack of visible label text may still be problematic for certain users. Some form of visible label is generally the best approach, both for accessibility and usability.