Bootstrap Forms

Bootstrap 4 has a lot to offer for creating some flawless forms various data input purposes in the websites.

We have many form layouts and contextual classes that we’ll learn about in this chapter. Let’s have a look:

Bootstrap’s Default Settings

There are some global styling features that the Form controls automatically get when used with Bootstrap 4.

The basic contextual class is .form and the .form-control class can be used with different form control fields.

Therefore, by default, any <input>, <textarea> or <select> element with class .form-control gets a width of 100%.

Bootstrap Form Layouts

Bootstrap forms can be developed and rendered in 3 layouts. These are namely:

  • Vertical form (default)
  • Horizontal form
  • Inline form

All of these three layouts follow some standard rules which are:

  • All the form controls will be wrapped in <div class="form-group"> element. This is necessary for optimum spacing.
  • The class .form-control has to be added to all textual <input>, <textarea>, and <select> elements

Bootstrap Vertical Form

The vertical form layout is the default layout for the bootstrap forms.

The code below illustrates a form developed in this layout.

The form contains two input fields, one checkbox, and a submit button:

Bootstrap Inline Form

Here are some necessary points to be kept in mind for inline form layout:

  • This layout renders forms with elements in line and left aligned. Labels are attached to these item alongside.
  • The layout is only applicable within viewports that have a width of at least 768px
  • The contextual class .form-inline needs to be added to the <form> element for inline layout

Here’s a sample code for inline forms:

Labels are necessary for the readability of the form.

The .sr class hides the lables for all the devices except scrren readers.

Bootstrap Horizontal Form

The form has a horizontal layout on screens, at least as wide as 768px.

Thus the labels on these screens are aligned horizontally next to the input fields.

However, if the screen width goes lower than 768px, the form acts as if in the vertical layout with labels on the top of the fields.

The contextual class used is .form-horizontal.

And the class .control-label should be necessarily added to all the <label> elements.

It is advisable to use Bootstrap’s predefined grid classes when using the horizontal layout for better alignment of labels and groups of form controls.

The code below illustrates everything about Horizontal form layout: