Forms

Input Group Sizing

Use the class for small input groups and for large inputs groups:

Small

Default

Large

Example

<form>  <div class=»input-group mb-3 input-group-sm»>    
<div class=»input-group-prepend»>      
<span class=»input-group-text»>Small</span>    </div>   
<input type=»text» class=»form-control»>  </div></form>
<form>  <div class=»input-group mb-3″>    <div
class=»input-group-prepend»>      <span
class=»input-group-text»>Default</span>    </div>   
<input type=»text» class=»form-control»>  </div></form><form>  <div
class=»input-group mb-3 input-group-lg»>    <div
class=»input-group-prepend»>      <span
class=»input-group-text»>Large</span>    </div>   
<input type=»text» class=»form-control»>  </div></form>

CSPs and embedded SVGs

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

  • Close button (used in alerts and modals)

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

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>

Grid options

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

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

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

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

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>

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.

Form Control Sizing

You can set heights and widths of forms using classes like .input-lg and .col-lg-* respectively. The following example demonstrates this −

<form role = "form">

   <div class = "form-group">
      <input class = "form-control input-lg" type = "text" placeholder =".input-lg">
   </div>

   <div class = "form-group">
      <input class = "form-control" type = "text" placeholder = "Default input">
   </div>

   <div class = "form-group">
      <input class = "form-control input-sm" type = "text" placeholder = ".input-sm">
   </div>
   
   <div class = "form-group"></div>
   
   <div class = "form-group">
      <select class = "form-control input-lg">
         <option value = "">.input-lg</option>
      </select>
   </div>
   
   <div class = "form-group">
      <select class = "form-control">
         <option value = "">Default select</option>
      </select>
   </div>
   
   <div class = "form-group">
      <select class = "form-control input-sm">
         <option value = "">.input-sm</option>
      </select>
   </div>

   <div class = "row">
      <div class = "col-lg-2">
         <input type = "text" class = "form-control" placeholder = ".col-lg-2">
      </div>
      
      <div class = "col-lg-3">
         <input type = "text" class = "form-control" placeholder = ".col-lg-3">
      </div>
      
      <div class = "col-lg-4">
         <input type = "text" class = "form-control" placeholder = ".col-lg-4">
      </div>
      
   </div>
</form>

How it works

Breaking it down, here’s how the grid system comes together:

  • Our grid supports six responsive breakpoints. Breakpoints are based on media queries, meaning they affect that breakpoint and all those above it (e.g., applies to , , , , and ). This means you can control container and column sizing and behavior by each breakpoint.

  • Containers center and horizontally pad your content. Use for a responsive pixel width, for across all viewports and devices, or a responsive container (e.g., ) for a combination of fluid and pixel widths.

  • Rows are wrappers for columns. Each column has horizontal (called a gutter) for controlling the space between them. This is then counteracted on the rows with negative margins to ensure the content in your columns is visually aligned down the left side. Rows also support modifier classes to and gutter classes to change the spacing of your content.

  • Columns are incredibly flexible. There are 12 template columns available per row, allowing you to create different combinations of elements that span any number of columns. Column classes indicate the number of template columns to span (e.g., spans four). s are set in percentages so you always have the same relative sizing.

  • Gutters are also responsive and customizable. Gutter classes are available across all breakpoints, with all the same sizes as our margin and padding spacing. Change horizontal gutters with classes, vertical gutters with , or all gutters with classes. is also available to remove gutters.

  • Sass variables, maps, and mixins power the grid. If you don’t want to use the predefined grid classes in Bootstrap, you can use our to create your own with more semantic markup. We also include some CSS custom properties to consume these Sass variables for even greater flexibility for you.

Be aware of the limitations and bugs around flexbox, like the .

Form Styles

By default, your forms will stack labels on top of controls and your controls
will grow to 100 percent of the available width. This is consistent with Bootstrap’s «mobile first» approach.

Inline Forms

To use an inline-layout form, use the option. To hide labels,
use the option, which keeps your labels accessible to those
using screen readers.

<%= bootstrap_form_for(@user, layout: :inline) do |f| %>
  <%= f.email_field :email, hide_label: true %>
  <%= f.password_field :password, hide_label: true %>
  <%= f.check_box :remember_me %>
  <%= f.submit %>
<% end %>

To skip label rendering at all, use option.

<%= f.password_field :password, skip_label: true %>

Horizontal Forms

To use a horizontal-layout form with labels to the left of the control, use the
option. You should specify both and
css classes as well (they default to and ).

In the example below, the checkbox and submit button have been wrapped in a
to keep them properly aligned.

<%= bootstrap_form_for(@user, layout: :horizontal, label_col: "col-sm-2", control_col: "col-sm-10") do |f| %>
  <%= f.email_field :email %>
  <%= f.password_field :password %>
  <%= f.form_group do %>
    <%= f.check_box :remember_me %>
  <% end %>
  <%= f.form_group do %>
    <%= f.submit %>
  <% end %>
<% end %>

The and css classes can also be changed per control:

<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
  <%= f.email_field :email %>
  <%= f.text_field :age, control_col: "col-sm-3" %>
  <%= f.form_group do %>
    <%= f.submit %>
  <% end %>
<% end %>

or default value can be changed in initializer:

# config/initializers/bootstrap_form.rb
module BootstrapForm
  class FormBuilder
    def default_label_col
      'col-sm-4'
    end
    def default_control_col
      'col-sm-8'
    end
    def default_layout
      # :default, :horizontal or :inline
      :horizontal
    end
  end
end

Control col wrapper class can be modified with . This option will preserve column definition:

<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
  <%= f.email_field :email %>
  <%= f.text_field :age, add_control_col_class: "additional-control-col-class" %>
  <%= f.form_group do %>
    <%= f.submit %>
  <% end %>
<% end %>

Custom Field Layout

The form-level can be overridden per field, unless the form-level layout was :

<%= bootstrap_form_for(@user, layout: :horizontal) do |f| %>
  <%= f.email_field :email %>
  <%= f.text_field :feet, layout: :default %>
  <%= f.text_field :inches, layout: :default %>
  <%= f.form_group do %>
    <%= f.submit %>
  <% end %>
<% end %>

A form-level can’t be overridden because of the way Bootstrap 4 implements in-line layouts. One possible work-around is to leave the form-level layout as default, and specify the individual fields as , except for the fields(s) that should be other than in-line.

Custom Form Element Styles

The option can be used to replace the browser default styles for check boxes and radio buttons with dedicated Bootstrap styled form elements. Here’s an example:

<%= bootstrap_form_for(@user) do |f| %>
  <%= f.email_field :email %>
  <%= f.password_field :password %>
  <%= f.check_box :remember_me, custom: true %>
  <%= f.submit "Log In" %>
<% end %>

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 six grid tiers.

First in DOM, no order applied

Second in DOM, with a larger order

Third in DOM, with an order of 1

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 in DOM, ordered last

Second in DOM, unordered

Third in DOM, ordered 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 .ms-auto

.col-md-3 .ms-md-auto
.col-md-3 .ms-md-auto

.col-auto .me-auto
.col-auto

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.

Input Group with Dropdown Button

Add a dropdown button in the input group. Note that you don’t need the .dropdown wrapper, as you normally would.

Dropdown button

Link 1
Link 2
Link 3

Example

<div class=»input-group mt-3 mb-3″>  <div class=»input-group-prepend»>    <button
type=»button» class=»btn btn-outline-secondary dropdown-toggle»
data-toggle=»dropdown»>      Dropdown
button    </button>    <div class=»dropdown-menu»>
      <a
class=»dropdown-item» href=»#»>Link 1</a>      <a class=»dropdown-item» href=»#»>Link 2</a>      <a class=»dropdown-item» href=»#»>Link 3</a>    </div>  </div>  <input type=»text»
class=»form-control» placeholder=»Username»></div>

Form Validation

You can use different validation classes to provide valuable feedback to
users. Add either or to the element,
depending on whether you want to provide validation feedback before or after
submitting the form. The input fields will have a green (valid) or red (invalid)
border to indicate what’s missing in the form. You can also add a
or message to tell the user explicitly what’s
missing, or needs to be done before submitting the form.

Example

In this example, we use to indicate what’s missing before submitting the form:

<form action=»/action_page.php» class=»was-validated»> 
<div class=»form-group»>    <label
for=»uname»>Username:</label>    <input type=»text»
class=»form-control» id=»uname» placeholder=»Enter username» name=»uname»
required>    <div class=»valid-feedback»>Valid.</div>   
<div class=»invalid-feedback»>Please fill out this field.</div> 
</div>  <div class=»form-group»>    <label
for=»pwd»>Password:</label>    <input type=»password»
class=»form-control» id=»pwd» placeholder=»Enter password» name=»pswd»
required>    <div class=»valid-feedback»>Valid.</div>   
<div class=»invalid-feedback»>Please fill out this field.</div> 
</div>  <div class=»form-group form-check»>   
<label class=»form-check-label»>      <input
class=»form-check-input» type=»checkbox» name=»remember» required> I agree on
blabla.      <div
class=»valid-feedback»>Valid.</div>      <div
class=»invalid-feedback»>Check this checkbox to continue.</div>   
</label>  </div>  <button type=»submit» class=»btn
btn-primary»>Submit</button></form>

Example

In this example, we use , which will add the validation effect AFTER the form has been submitting (if there’s anything missing).
Note that you will also have to add some jQuery code for this example to work
properly:

<form action=»/action_page.php» class=»needs-validation»
novalidate> 
<div class=»form-group»>    <label
for=»uname»>Username:</label>    <input type=»text»
class=»form-control» id=»uname» placeholder=»Enter username» name=»uname»
required>    <div class=»valid-feedback»>Valid.</div>   
<div class=»invalid-feedback»>Please fill out this field.</div> 
</div>  <div class=»form-group»>    <label
for=»pwd»>Password:</label>    <input type=»password»
class=»form-control» id=»pwd» placeholder=»Enter password» name=»pswd»
required>    <div class=»valid-feedback»>Valid.</div>   
<div class=»invalid-feedback»>Please fill out this field.</div> 
</div>  <div class=»form-group form-check»>   
<label class=»form-check-label»>      <input
class=»form-check-input» type=»checkbox» name=»remember» required> I agree on
blabla.      <div
class=»valid-feedback»>Valid.</div>      <div
class=»invalid-feedback»>Check this checkbox to continue.</div>   
</label>  </div>  <button type=»submit» class=»btn
btn-primary»>Submit</button></form><script>//
Disable form submissions if there are invalid fields(function() {  ‘use strict’; 
window.addEventListener(‘load’, function() {    // Get the
forms we want to add validation styles to    var forms =
document.getElementsByClassName(‘needs-validation’);    //
Loop over them and prevent submission    var validation =
Array.prototype.filter.call(forms, function(form) {     
form.addEventListener(‘submit’, function(event) {       
if (form.checkValidity() === false) {         
event.preventDefault();         
event.stopPropagation();        }       
form.classList.add(‘was-validated’);      },
false);    });  }, false);})();</script>

❮ Previous
Next ❯

Approach

Browser default checkboxes and radios are replaced with the help of , a series of classes for both input types that improves the layout and behavior of their HTML elements, that provide greater customization and cross browser consistency. Checkboxes are for selecting one or several options in a list, while radios are for selecting one option from many.

Structurally, our s and s are sibling elements as opposed to an within a . This is slightly more verbose as you must specify and attributes to relate the and . We use the sibling selector () for all our states, like or . When combined with the class, we can easily style the text for each item based on the ’s state.

Our checks use custom Bootstrap icons to indicate checked or indeterminate states.

Отключенные формы

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

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

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

Community

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

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

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

Z-index

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

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

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

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

Sass

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

Variables

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

Example usage

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

Main content
Secondary content

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

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.

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.

Custom Checkbox

To create a custom checkbox, wrap a container element, like <div>, with a
class of and around the checkbox. Then add the to the input with type=»checkbox».

Tip: If you use labels for accompanying text, add the class to it.
Note that the value of the for attribute should match the id of the checkbox:

Custom checkbox

Default checkbox

Example

<form>  <div class=»custom-control custom-checkbox»>   
<input type=»checkbox» class=»custom-control-input» id=»customCheck»
name=»example1″>   
<label class=»custom-control-label» for=»customCheck»>Check this custom
checkbox</label>  </div></form>

Доступность

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

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

  • Элементы скрыты с помощью класса
  • Указание на существующий элемент, который может действовать как метка, используя
  • Предоставление атрибута
  • Явная установка доступного имени для элемента с помощью

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

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

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.

Align content

Use utilities on flexbox containers to align flex items together on the cross axis. Choose from (browser default), , , , , or . To demonstrate these utilities, we’ve enforced and increased the number of flex items.

Heads up! This property has no effect on single rows of flex items.

Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item

Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item

Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item

Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item

Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item

Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item
Flex item

Responsive variations also exist for .

Горизонтальная форма

Вы можете использовать классы сетки 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 нет.

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

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

Adblock
detector