Bootstrap Forms

Your will discover how to use Bootstrap to design sophisticated form layouts in this lesson.


Creating Forms with Bootstrap

HTML forms are essential components of web pages and applications. However, manually creating form layouts and styling each form control using CSS can be a tedious and monotonous task. Luckily, Bootstrap simplifies this process by offering a set of pre-defined classes that handle the styling and alignment of form controls like labels, input fields, select boxes, text areas, and buttons.

Bootstrap provides three distinct form layouts:

  • Vertical Form (default form layout): This layout arranges form controls in a vertical stack, with labels positioned above the corresponding controls.
  • Horizontal Form: In this layout, labels and form controls are aligned side-by-side using Bootstrap's grid classes.
  • Inline Form: This layout condenses the form by displaying a series of form controls and buttons in a single horizontal row.

The following section will provide a detailed overview of these form layouts, as well as various other Bootstrap components related to forms.

Creating Vertical Form Layout

To create vertical form layouts, you can simply use the pre-defined margin utility classes to group labels, form controls, optional form text, and form validation messages. An example of this layout places form controls in a vertical stack with labels on top.

In the next chapter, you will learn about custom checkboxes and other customized form controls.

<div class="m-4">
    <form action="confirmation.php" method="post">
        <div class="mb-3">
            <label class="form-label" for="inputEmail">Email</label>
            <input type="email" class="form-control" id="inputEmail" placeholder="Email" required>
        </div>
        <div class="mb-3">
            <label class="form-label" for="inputPassword">Password</label>
            <input type="password" class="form-control" id="inputPassword" placeholder="Password" required>
        </div>
        <button type="submit" class="btn btn-primary">Sign in</button>
    </form>
</div>

The following chapters will cover custom checkboxes and other custom form controls.

Note: For textual form controls, such as <input> and <textarea>, the required class is .form-control, while <select> elements need the class .form-select for general styling. These classes also ensure that the form controls span 100% of their container width. To adjust their width or make them appear inline, you can leverage Bootstrap's predefined grid classes.

Tip: It is advisable to use margin-bottom utility classes (e.g., mb-2, mb-3, etc.) to introduce vertical spacing between form groups. This approach ensures a consistent and non-collapsing form layout by applying single-direction margin throughout.


Creating Horizontal Form Layout

In addition to vertical forms, Bootstrap allows you to create horizontal form layouts. For this, you need to add the .row class to form groups and use the .col-*-* grid classes to specify the width of labels and controls. This aligns the labels and form controls side-by-side.

Make sure to use the class .col-form-label on your <label> elements to ensure they are vertically centered with their associated form controls. Let's see an example of how this works:

<div class="m-4">
    <form action="confirmation.php" method="post">
        <div class="row mb-3">
            <label for="inputEmail" class="col-sm-2 col-form-label">Email</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="Email1" placeholder="Email" required>
            </div>
        </div>
        <div class="row mb-3">
            <label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" id="Password1" placeholder="Password" required>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-10 offset-sm-2">
                <button type="submit" class="btn btn-primary">Sign in</button>
            </div>
        </div>
    </form>
</div>

Creating Inline Form Layout

If you want to display a series of form controls and buttons in a single horizontal row for a more compact layout, you can easily achieve this using Bootstrap's grid classes.

Here's an example to demonstrate how it works:

<div class="m-4">
    <form action="confirmation.php" method="post">
        <div class="row align-items-center g-3">
            <div class="col-auto">
                <label class="visually-hidden" for="inputEmail">Email</label>
                <input type="email" class="form-control" id="Email2" placeholder="Email" required>
            </div>
            <div class="col-auto">
                <label class="visually-hidden" for="inputPassword">Password</label>
                <input type="password" class="form-control" id="Password2" placeholder="Password" required>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-primary">Sign in</button>
            </div>
        </div>
    </form>
</div>

To see samples of a few gorgeously created Bootstrap forms, visit the snippets area.

Tip: Including a label for every form input is recommended to ensure proper accessibility for screen readers. However, for inline form layouts, you can hide the labels using the .visually-hidden class, making them accessible only to screen readers.


Creating Responsive Form Layout

To make your forms responsive, you can utilize the grid classes with specific breakpoints.

The following example will create a form layout that is inline on medium devices and larger (viewport width ≥768px) and becomes vertically stacked on smaller viewports.

<div class="m-4">
    <form action="confirmation.php" method="post">
        <div class="row align-items-center g-3">
            <div class="col-md-auto col-12">
                <label class="form-label d-md-none" for="inputEmail">Email</label>
                <input type="email" class="form-control" id="Email3" placeholder="Email" required>
            </div>
            <div class="col-md-auto col-12">
                <label class="form-label d-md-none" for="inputPassword">Password</label>
                <input type="password" class="form-control" id="Password3" placeholder="Password" required>
            </div>
            <div class="col-md-auto col-12">
                <button type="submit" class="btn btn-primary">Sign in</button>
            </div>
        </div>
    </form>
</div>

Creating Static Form Control

In some cases, you may only need to display plain text next to a form label instead of an interactive form control.

To achieve this, simply replace the .form-control class with .form-control-plaintext and apply the readonly attribute. This class removes the default styling from the form field while preserving correct margins and padding.

<div class="m-4">
    <form action="confirmation.php" method="post">
        <div class="row mb-3">
            <label for="inputEmail" class="col-sm-2 col-form-label">Email</label>
            <div class="col-sm-10">
                <input type="email" readonly class="form-control-plaintext" id="Email4" value="suresh@simmanchith.com">
            </div>
        </div>
        <div class="row mb-3">
            <label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" id="Password4" placeholder="Password" required>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-10 offset-sm-2">
                <button type="submit" class="btn btn-primary">Sign in</button>
            </div>
        </div>

Column Sizing of Form Controls

If you want to match the size of your inputs, textareas, and select boxes to the Bootstrap grid column sizes, you can place these form controls (i.e., <input>, <textarea>, and <select>) within grid columns.

This way, the form controls will adjust according to the specified column sizes.

<div class="m-4">
    <div class="row g-3">
        <div class="col-6">
            <input type="text" class="form-control" placeholder="City">
        </div>
        <div class="col-4">
            <select class="form-select">
                <option>State</option>
            </select>
        </div>
        <div class="col-2">
            <input type="text" class="form-control" placeholder="Zip">
        </div>
    </div>
</div>

Placing Checkboxes and Radio Buttons Inline

By default, with the class .form-check, any number of custom checkboxes and radio buttons that are immediate siblings will be vertically stacked and spaced appropriately.

However, if you want to place these custom checkboxes and radio buttons inline (in the same line), you can do so by adding the class .form-check-inline to the .form-check element.

<div class="m-4">
    <h3 class="mb-4">Default Placement of Checkboxes</h3>
    <div class="row">
        <div class="col-12">
            <div class="form-check mb-3">
                <input type="checkbox" class="form-check-input" name="hobbies" id="checkMusic">
                <label class="form-check-label" for="checkMusic">Music</label>
            </div>
            <div class="form-check">
                <input type="checkbox" class="form-check-input" name="hobbies" id="checkReading" checked>
                <label class="form-check-label" for="checkReading">Reading novels</label>
            </div>
        </div>
    </div>

Similarly, you can also place the radio buttons inline, as shown in the following example:

<div class="m-4">
    <h3 class="mb-4">Default Placement of Radio Buttons</h3>
    <div class="row">
        <div class="col-12">
            <div class="form-check mb-3">
                <input type="radio" class="form-check-input" name="gender" id="radioMale" checked>
                <label class="form-check-label" for="radioMale">Male</label>
            </div>
            <div class="form-check">
                <input type="radio" class="form-check-input" name="gender" id="radioFemale">
                <label class="form-check-label" for="radioFemale">Female</label>
            </div>
        </div>
    </div>

Adding Help Text to Form Controls

To effectively guide users in entering correct data into a form, you can add help text for form controls in a well-organized manner. To place block-level help text, you can use the class .form-text, which is typically displayed at the bottom of the form control. Here's an example:

<div class="m-4">
    <label class="form-label" for="inputPassword">Password</label>
    <input type="password" class="form-control" id="Password5">
    <div class="form-text">
       must not include spaces and be between 8 and 20 characters long, including letters, numbers, and special characters.
    </div>
</div>

Alternatively, you can use the <small> element to add inline help text without the need for the .form-text class. This example demonstrates how to implement it:

<div class="m-4">
    <div class="row align-items-center g-3">
        <div class="col-auto">
            <label class="col-form-label" for="inputPassword">Password</label>
        </div>
        <div class="col-auto">
            <input type="password" class="form-control" id="Password6">
        </div>
        <div class="col-auto">
            <span class="form-text">Must be 8-20 characters long.</span>
        </div>
    </div>
</div>

Creating Disabled Form Controls

Disabling individual form controls such as <input>, <textarea>, or <select> is straightforward in Bootstrap. Simply add the disabled attribute to the respective elements, and Bootstrap will handle the rest. Here's an example:

<div class="m-4">
    <input type="text" class="form-control mb-3" placeholder="Disabled input" disabled>
    <textarea class="form-control mb-3" placeholder="Disabled textarea" disabled></textarea>
    <select class="form-select" disabled>
        <option>Disabled select</option>
    </select>
</div>

If you need to disable all controls within a <form> at once, you can place them inside a <fieldset> element and apply the disabled attribute to it. The following example illustrates this:

<div class="m-4">
    <form action="confirmation.php" method="post">
        <fieldset disabled>
            <div class="row mb-3">
                <label for="inputEmail" class="col-sm-2 col-form-label">Email</label>
                <div class="col-sm-10">
                    <input type="email" class="form-control" id="Email5" placeholder="Email" required>
                </div>
            </div>

Creating Readonly Inputs

To prevent the modification of values in an input or textarea, you can use the readonly boolean attribute. Read-only inputs appear with a lighter background (similar to disabled inputs) but retain the standard text cursor. See the example below to understand how it works:

<div class="m-4">
    <input type="text" class="form-control mb-2" value="This input value cannot be changed." readonly>
    <textarea rows="3" class="form-control" readonly>This textarea value cannot be changed.</textarea>
</div>

Height Sizing of Form Controls

You can easily adjust the height of text inputs and select boxes to match button sizes using form control height sizing classes like .form-control-lg and .form-control-sm. Here's an example:

<div class="m-4">
    <div class="row mb-3">
        <label class="col-sm-2 col-form-label col-form-label-lg">Email</label>
        <div class="col-sm-10">
            <input type="email" class="form-control form-control-lg" placeholder="Large input">
        </div>
    </div>

Tip: For resizing labels according to form controls, use the classes .col-form-label-lg or .col-form-label-sm on the <label> or <legend> elements.

Similarly, you can create larger and smaller variants of select boxes with the .form-select-lg and .form-select-sm classes on the <select> element:

<div class="m-4">
    <div class="row mb-3">
        <label class="col-sm-2 col-form-label col-form-label-lg">State</label>
        <div class="col-sm-10">
            <select class="form-select form-select-lg">
                <option>Large select</option>
            </select>
        </div>
    </div>

Bootstrap Form Validation

Bootstrap simplifies form validation on the client-side by utilizing the browser's native form validation API. It applies validation styles through CSS pseudo-classes :invalid and :valid on <input>, <select>, and <textarea> elements.

Let's see an example to understand how it works:

<div class="m-4">
    <form action="confirmation.php" class="needs-validation" method="post" novalidate>
        <div class="mb-3">
            <label class="form-label" for="inputEmail">Email</label>
            <input type="email" class="form-control" id="Email6" placeholder="Email" required>
            <div class="invalid-feedback">Please enter a valid email address.</div>
        </div>

Note: To provide custom Bootstrap form validation messages, you can disable the browser's default feedback tooltips by adding the novalidate boolean attribute to the <form> element.

This allows you to implement custom JavaScript code that displays error messages and prevents form submission if there are invalid fields.

<div class="m-4">
    <form action="confirmation.php" class="needs-validation" method="post" novalidate>
        <div class="mb-3">
            <label class="form-label" for="inputEmail">Email</label>
            <input type="email" class="form-control" id="Email7" placeholder="Email" required>
            <div class="invalid-feedback">Please enter a valid email address.</div>
        </div>

Tip: After form submission, to reset the form's appearance programmatically, you can remove the .was-validated class from the <form> element. Bootstrap automatically applies this class when you click the submit button.

For server-side validation, you can use the .is-invalid and .is-valid classes to indicate invalid and valid form fields, respectively. Additionally, the .invalid-feedback and .valid-feedback classes are supported for providing feedback messages. Here's an example:

<div class="m-4">
    <form>
        <div class="mb-3">
            <label class="form-label" for="inputEmail">Email</label>
            <input type="email" class="form-control is-valid" id="Email8" placeholder="Email" value="suresh@simmanchith.com" required>
            <div class="valid-feedback">Good! Your email address looks valid.</div>
        </div>

If you prefer displaying validation feedback text in tooltip style, you can swap the .{valid|invalid}-feedback classes for .{valid|invalid}-tooltip classes.

Just make sure to apply the style position: relative or the class .position-relative to the parent element for proper tooltip positioning. Here's an example:

<div class="m-4">
        <form action="confirmation.php" class="needs-validation" method="post" novalidate>
            <div class="mb-3 position-relative">
                <label class="form-label" for="inputEmail">Email</label>
                <input type="email" class="form-control" id="Email9" placeholder="Email" required>                
                <div class="invalid-tooltip">Please enter a valid email address.</div>
            </div>

Supported Form Controls in Bootstrap

Bootstrap supports all standard HTML form controls as well as new HTML5 input types such as datetime, number, email, url, search, range, color, and more. The following example demonstrates the usage of standard form controls with Bootstrap.

<div class="m-4">
    <h1 class="border-bottom pb-3 mb-4">Registration Form</h1>
    <form class="needs-validation" action="confirmation.php" method="post" novalidate>
        <div class="row mb-3">
            <label class="col-sm-3 col-form-label" for="firstName">First Name:</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="firstName" placeholder="First Name" required>
            </div>
        </div>

FAQ

How do you create a basic form using Bootstrap?

You can create a basic form using the <form> element and Bootstrap's form classes. This provides a clean and consistent structure for your form, helping to maintain a cohesive design across your application.

<form>
    <!-- Form elements go here -->
</form>

What class should you add to a form to make it look inline?

You can use the .form-inline class to create an inline form. This is particularly useful when you want the form elements to be displayed horizontally, making the form more compact.

<form class="form-inline">
    <!-- Inline form elements go here -->
</form>

How can you create a horizontal form layout in Bootstrap?

Use the .form-horizontal class to create a horizontal form. This style is beneficial when you want a more traditional, side-by-side layout for your form controls.

<form class="form-horizontal">
    <!-- Horizontal form elements go here -->
</form>

What is the purpose of the .form-group class in Bootstrap forms?

The .form-group class is used to group form elements and apply styling to the entire group. It helps maintain proper spacing and alignment, ensuring a visually appealing and consistent form layout.

<div class="form-group">
    <label for="exampleInput">Label</label>
    <input type="text" class="form-control" id="exampleInput" placeholder="Enter text">
</div>

How can you add labels to form elements in Bootstrap?

Use the <label> element and associate it with form controls using the for attribute. This not only enhances accessibility but also provides a clear description of each form field.

<div class="form-group">
    <label for="exampleInput">Label</label>
    <input type="text" class="form-control" id="exampleInput" placeholder="Enter text">
</div>

How do you create a form with different sizes of input elements?

You can use classes like .form-control-lg or .form-control-sm for larger or smaller input elements, allowing you to customize the appearance based on your design preferences or the importance of the input.

<input type="text" class="form-control form-control-lg" placeholder="Large input">
<input type="text" class="form-control" placeholder="Default input">
<input type="text" class="form-control form-control-sm" placeholder="Small input">

How can you create a disabled input field in Bootstrap forms?

Add the disabled attribute to the input element or use the .form-control class along with the .disabled class. This prevents user interaction with the input field.

<input type="text" class="form-control" placeholder="Disabled Input" disabled>

How do you create a read-only input field in Bootstrap forms?

Add the readonly attribute to the input element. This allows users to view the content but prevents them from modifying it.

<input type="text" class="form-control" value="Read-only text" readonly>

How can you create a form with a dropdown menu in Bootstrap?

Use the <select> element with the .form-control class for a basic dropdown. This provides users with a predefined set of options to choose from.

<select class="form-control">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

How do you create a multi-select dropdown in Bootstrap forms?

Add the multiple attribute to the <select> element. This allows users to select multiple options from the dropdown.

<select class="form-control" multiple>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

What is the purpose of the .form-check class in Bootstrap forms?

The .form-check class is used for custom-styled checkboxes and radio buttons. It provides a consistent and visually appealing way to present and interact with boolean options.

<div class="form-check">
    <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
    <label class="form-check-label" for="defaultCheck1">
        Default checkbox
    </label>
</div>

How can you create a Bootstrap form with a textarea for multiline input?

You can use the <textarea> element with the .form-control class for a multiline input:

<div class="form-group">
    <label for="exampleTextarea">Textarea</label>
    <textarea class="form-control" id="exampleTextarea" rows="3"></textarea>
</div>

What is the purpose of the .form-check-inline class in Bootstrap forms?

The .form-check-inline class is used to display checkboxes or radio buttons inline, making them appear on the same line rather than stacking vertically:

<div class="form-check form-check-inline">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1">
    <label class="form-check-label" for="inlineCheckbox1">Option 1</label>
</div>

How can you create a Bootstrap form with a range input?

You can use the <input> element with type="range" and the .form-control-range class for a range input:

<div class="form-group">
    <label for="formControlRange">Example Range Input</label>
    <input type="range" class="form-control-range" id="formControlRange">
</div>

How do you create a Bootstrap form with a file input for uploading files?

Use the <input> element with type="file" and the .form-control-file class for a file input:

<div class="form-group">
    <label for="exampleFormControlFile">Choose File</label>
    <input type="file" class="form-control-file" id="exampleFormControlFile">
</div>

How can you add a submit button to a Bootstrap form?

You can use the <button> element with type="submit" and the .btn and .btn-primary classes for a styled submit button:

<button type="submit" class="btn btn-primary">Submit</button>

How do you create a Bootstrap form with inline form validation feedback?

Utilize the .was-validated class on the form and the .valid-feedback and .invalid-feedback classes on individual form elements for validation feedback:

<form class="was-validated">
    <div class="form-group">
        <label for="validationInput">Input</label>
        <input type="text" class="form-control is-invalid" id="validationInput" required>
        <div class="invalid-feedback">Please provide a valid input.</div>
    </div>
</form>

How can you create a Bootstrap form with a pre-filled and disabled input field?

You can use the value attribute to pre-fill the input field and the disabled attribute to make it read-only:

<div class="form-group">
    <label for="disabledInput">Disabled Input</label>
    <input type="text" class="form-control" id="disabledInput" value="Pre-filled content" disabled>
</div>

How do you create a Bootstrap form with a checkbox that toggles the visibility of another input field?

Utilize JavaScript along with the .d-none class for conditional visibility:

<div class="form-check">
    <input class="form-check-input" type="checkbox" id="toggleInput">
    <label class="form-check-label" for="toggleInput">Toggle Input</label>
</div>
<div class="form-group">
    <input type="text" class="form-control d-none" id="conditionalInput" placeholder="Conditional Input">
</div>
<script>
    document.getElementById('toggleInput').addEventListener('change', function () {
        document.getElementById('conditionalInput').classList.toggle('d-none');
    });
</script>

How can you customize the appearance of a Bootstrap form for different states, such as focus or hover?

Use the :focus, :hover, and other pseudo-classes in CSS to customize the appearance for different states:

.form-control:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.form-control:hover {
    border-color: #007bff;
}

How can you create a Bootstrap form with a date input using the datepicker component?

You can use the Bootstrap Datepicker plugin along with the .datepicker class for a date input:

<div class="form-group">
    <label for="datepicker">Select Date</label>
    <input type="text" class="form-control datepicker" id="datepicker">
</div>

How can you create a Bootstrap form with a tooltip on a form element for additional information?

Use the Bootstrap Tooltip component and add the data-toggle and data-placement attributes to the form element:

<div class="form-group">
    <label for="inputWithTooltip" data-toggle="tooltip" data-placement="top" title="Additional information">Input with Tooltip</label>
    <input type="text" class="form-control" id="inputWithTooltip">
</div>
<script>
    $(function () {
        $('[data-toggle="tooltip"]').tooltip();
    });
</script>

Conclusion

Bootstrap proves to be a powerful framework for form creation and design, offering a comprehensive set of tools for crafting web forms that are not only visually appealing but also highly functional.

When it comes to designing web forms, Bootstrap provides the flexibility to create user-friendly interfaces. The framework excels in styling form elements, allowing designers to tailor the appearance of each element to match the overall aesthetic of the project. This extends to customizing form layouts to suit various screen sizes, ensuring a seamless experience across devices.

Bootstrap's emphasis on responsive form elements facilitates the creation of interfaces that adapt dynamically to different screen sizes. The framework supports both vertical and horizontal form styling, providing options for fluid layouts that enhance the user experience, especially on mobile devices.

For scenarios where a more static design is desired, Bootstrap accommodates fixed-width form layouts. This versatility allows designers to choose between responsive and non-responsive form elements based on project requirements. Moreover, Bootstrap extends its functionality by enabling the addition of help text to form elements. This can include tooltips and additional guidance, enhancing the user experience and providing clarity.

The framework also caters to scenarios where form elements need to be in a disabled or readonly state, offering the necessary flexibility for different use cases. Additionally, designers can fine-tune the appearance of form controls by customizing height sizes, ensuring a cohesive and visually pleasing design.

For more complex forms, Bootstrap supports the creation of multi-column form layouts, providing a structured and organized way to present information. This feature is particularly beneficial when dealing with large sets of data or complex input scenarios.