Bootstrap makes it easy to style different types of forms with the simple HTML markup and extended classes. Bootstrap provides three types of form layouts:
- Vertical form (default)
- In-line form
- Horizontal form
<form role = "form">
<div class = "form-group">
<label for = "name">Name</label>
<input type = "text" class = "form-control" id = "name" placeholder = "Enter Name">
</div>
<div class = "form-group">
<label for = "inputfile">File input</label>
<input type = "file" id = "inputfile">
</div>
<div class = "checkbox">
<label><input type = "checkbox"> Check me out</label>
</div>
<button type = "submit" class = "btn btn-default">Submit</button>
</form>
Basic Form
To create a basic form, you need to do the following:
- Add a role form to the parent <form> element.
- Wrap labels and controls in a <div> with class .form-group. This is needed for optimum spacing.
- Add a class of .form-control to all textual <input>, <textarea> and <select> elements.
Inline Form
To create a form where all of the elements are inline, left aligned and labels are alongside, add the class .form-inline to the <form> tag.
Horizontal Form
To create horizontal form, add class .form-horizontal to the <form> element. Also, add class .control-label to all <label> elements.
Form Control in Bootstrap 4
In bootstrap 4, you are not required to add a role form to the parent <form> element.
Textual form controls like <input>, <select>, and <textarea>, are styled with the .form-control class. For file inputs, change the .form-control for .form-control-file.
You can set the height using classes like .form-control-lg and .form-control-sm.
Read Only Input
Add the readonly boolean attribute on an input to prevent modification of value of the input. Read-only inputs appear lighter (just like disabled inputs), but retain the standard cursor.
If you want to have <input readonly> elements in your form styled as plain text, use the .form-control-plaintext class to remove the default form field styling and preserve the correct margin and padding.
Checkbox and Radio
Checkboxes are for selecting one or several options in a list, while radios are for selecting one option from many. By default, any number of checkboxes and radios that are immediate sibling are vertically stacked and appropriately spaced with .form-check.
You can group checkboxes or radios on the same horizontal row by adding .form-check-inline to any .form-check.