How to Create Form Layouts with Bootstrap ?
Last Updated :
06 May, 2024
Form Layouts in Bootstrap refer to the arrangement and presentation of form elements within a web page. To create Form Layouts with Bootstrap, utilize grid system classes to structure forms horizontally or vertically, and enhance them with input groups, inline forms, and responsive designs for improved user interaction and aesthetics.
Below Bootstrap layouts can be used to create a form layout:
Vertical Form Layout
In a vertical form layout, form elements are stacked on top of each other, making efficient use of vertical space. This layout is suitable for forms with a small to moderate number of fields.
Example: The below code creates a vertical form layout using the Bootstrap classes.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Sign In</title>
<link href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
.is-invalid {
border-color: #dc3545;
}
.invalid-feedback {
display: none;
/* Hide validation messages by default */
color: #dc3545;
}
</style>
</head>
<body>
<div class="container">
<h1>Sign In</h1>
<form id="signInForm" novalidate>
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text"
class="form-control"
id="username"
placeholder="Enter your username" required>
<div class="invalid-feedback">
Please enter a valid username.
</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<div class="input-group">
<input type="password"
class="form-control"
id="password"
placeholder="Enter your password" required
pattern="(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}"
title="invalid Password">
<button class="btn btn-outline-secondary"
type="button"
id="togglePassword">
Show
</button>
</div>
<div class="invalid-feedback">
Password must contain at least one
uppercase letter, one digit,
one special character, and be at
least 8 characters long.
</div>
</div>
<div class="mb-3">
<label for="email"
class="form-label">
Email
</label>
<input type="email"
class="form-control"
id="email"
placeholder="Enter your email address" required
pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$">
<div class="invalid-feedback">
Please enter a valid email address.
</div>
</div>
<button type="submit"
class="btn btn-primary">
Sign In
</button>
</form>
</div>
<script>
const signInForm = document.getElementById('signInForm');
const passwordField = document.getElementById('password');
const togglePasswordButton = document.getElementById('togglePassword');
const inputFields = document.querySelectorAll('input');
togglePasswordButton.addEventListener('click', function () {
if (passwordField.type === 'password') {
passwordField.type = 'text';
togglePasswordButton.textContent = 'Hide';
} else {
passwordField.type = 'password';
togglePasswordButton.textContent = 'Show';
}
});
signInForm.addEventListener('submit', function (event) {
if (!signInForm.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
signInForm.classList.add('was-validated');
// Show validation feedback messages after form submission attempt
const invalidInputs = signInForm.querySelectorAll(':invalid');
invalidInputs.forEach(function (input) {
input.classList.add('is-invalid');
input.nextElementSibling.style.display = 'block';
});
});
inputFields.forEach(function (input) {
input.addEventListener('input', function () {
if (input.checkValidity()) {
input.classList.remove('is-invalid');
input.nextElementSibling.style.display = 'none';
}
});
});
</script>
</body>
</html>
Output:
Form Layouts with Bootstrap Example OutputIn a horizontal form layout, form elements are arranged side by side, with labels aligned to the left of their corresponding input fields. This layout is ideal for forms with longer labels or when horizontal space is abundant.
Example: The below code implements Bootstrap classes to create a Horizontal form.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Sign In</title>
<link href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<style>
.is-invalid {
border-color: #dc3545;
}
.invalid-feedback {
display: none;
/* Hide validation messages by default */
color: #dc3545;
}
</style>
</head>
<body>
<div class="container">
<h1>Horizontal Form Layout</h1>
<form id="signInForm" novalidate>
<div class="row mb-3">
<label for="username" class="col-sm-2 col-form-label">
Username
</label>
<div class="col-sm-10">
<input type="text"
class="form-control"
id="username"
placeholder="Enter your username" required>
<div class="invalid-feedback">
Please enter a valid username.
</div>
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-sm-2 col-form-label">
Password
</label>
<div class="col-sm-10">
<div class="input-group">
<input type="password"
class="form-control"
id="password" placeholder="Enter your password"
required pattern="(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).{8,}"
title="Invalid Password.">
<button class="btn btn-outline-secondary"
type="button"
id="togglePassword">
Show
</button>
</div>
<div class="invalid-feedback">
Password must contain at least one uppercase letter,
one digit, one special character, and be at
least 8 characters long.
</div>
</div>
</div>
<div class="row mb-3">
<label for="email"
class="col-sm-2 col-form-label">
Email
</label>
<div class="col-sm-10">
<input type="email"
class="form-control"
id="email"
placeholder="Enter your email address" required
pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$">
<div class="invalid-feedback">
Please enter a valid email address.
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-10 offset-sm-2">
<button type="submit" class="btn btn-primary">
Sign In
</button>
</div>
</div>
</form>
</div>
<script>
const signInForm = document.getElementById('signInForm');
const passwordField = document.getElementById('password');
const togglePasswordButton = document.getElementById('togglePassword');
const inputFields = document.querySelectorAll('input');
togglePasswordButton.addEventListener('click', function () {
if (passwordField.type === 'password') {
passwordField.type = 'text';
togglePasswordButton.textContent = 'Hide';
} else {
passwordField.type = 'password';
togglePasswordButton.textContent = 'Show';
}
});
signInForm.addEventListener('submit', function (event) {
if (!signInForm.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
signInForm.classList.add('was-validated');
// Show validation feedback messages after form submission attempt
const invalidInputs = signInForm.querySelectorAll(':invalid');
invalidInputs.forEach(function (input) {
input.classList.add('is-invalid');
input.nextElementSibling.style.display = 'block';
});
});
inputFields.forEach(function (input) {
input.addEventListener('input', function () {
if (input.checkValidity()) {
input.classList.remove('is-invalid');
input.nextElementSibling.style.display = 'none';
}
});
});
</script>
</body>
</html>
Output:
Form Layouts with Bootstrap Example OutputIn an inline form layout, form elements are displayed horizontally in a single line, with labels and input fields inline. This layout is useful for compact forms or when horizontal space is limited.
Example: The below code creates a inline form using the Bootstrap form classes.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1">
<title>Inline Form</title>
<link rel="stylesheet"
href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity=
"sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous">
</head>
<body>
<div class="container-fluid bg-success
d-flex justify-content-center
align-items-center"
style="min-height: 100vh;">
<form id="inlineForm"
class="row row-cols-lg-auto
g-3 align-items-center"
onsubmit="return validateForm()">
<div class="col-12">
<label class="visually-hidden"
for="inlineFormInputGroupUsername">
Username
</label>
<div class="input-group">
<div class="input-group-text">@</div>
<input type="text"
class="form-control"
id="inlineFormInputGroupUsername"
placeholder="Username" required>
</div>
</div>
<div class="col-12">
<label class="visually-hidden"
for="inlineFormInputPassword">
Password
</label>
<div class="input-group">
<input type="password"
class="form-control"
id="inlineFormInputPassword"
placeholder="Password" required>
<button type="button"
class="btn btn-outline-secondary
bg-primary
text-light
border-primary"
onclick="togglePassword()">
Show/Hide
</button>
</div>
</div>
<div class="col-12">
<label class="visually-hidden"
for="inlineFormSelectPref">
Preference
</label>
<select class="form-select"
id="inlineFormSelectPref" required>
<option selected disabled>Choose...</option>
<option value="1">Mumbai</option>
<option value="2">Delhi</option>
<option value="3">Noida</option>
</select>
</div>
<div class="col-12">
<button type="submit"
class="btn btn-primary">
Submit
</button>
</div>
</form>
</div>
<script src=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity=
"sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script>
<script>
function validateForm() {
const username = document.getElementById(
"inlineFormInputGroupUsername").value;
const password = document.getElementById(
"inlineFormInputPassword").value;
const preference = document.getElementById(
"inlineFormSelectPref").value;
if (!username || !password || !preference) {
alert("Please fill in all fields");
return false;
}
if (password.length < 8) {
alert("Password must be at least 8 characters long");
return false;
}
return true;
}
function togglePassword() {
const passwordField = document.getElementById("inlineFormInputPassword");
if (passwordField.type === "password") {
passwordField.type = "text";
} else {
passwordField.type = "password";
}
}
</script>
</body>
</html>
Output:
Form Layouts with Bootstrap Example Output
Similar Reads
How to Create a Four-Column Layout with Bootstrap ?
In Bootstrap, creating a column layout is important for organizing content into a structured grid system. A four-column layout allows for efficient arrangement of content, such as displaying courses, products, or services, with flexibility in responsiveness for various screen sizes. Below are the ap
2 min read
How to create bootstrap panel with footer ?
Bootstrap is a free open source tool for designing modern and responsive websites and web applications. It is the most popular tool for developing websites that are responsive and also beautiful. Bootstrap Panels are boxes with or without a border. You may want to put your contents inside some boxes
2 min read
How to Create Custom Input File with Bootstrap?
This article will show you how to create a custom input file using the Bootstrap 5 library. Bootstrap 5 has various styling file input classes and functionalities that can enhance the visual appearance of custom file input. There are two different approaches along with their implementation. In both
3 min read
How to Create a Bootstrap Form Validation ?
A Bootstrap Form Validation ensures that user input complies with established standards before submission, improves the user experience, and minimizes server-side processing for incorrect inputs. We can add client-side validation to their forms by using two different methods including Bootstrap buil
3 min read
How to Create a Responsive Layout with React Bootstrap ?
Creating a responsive layout with React Bootstrap means designing a web page that adapts and looks good on various screen sizes and devices. React Bootstrap provides responsive components and grid system classes that help in organizing and scaling content effectively, ensuring a seamless user experi
3 min read
How to create a form within dropdown menu using Bootstrap ?
A Dropdown menu is used to allow the user to choose the content from the menu as per their requirement and it is used to save screen space and avoid the long scrolling of the web pages. In web design, we often come in a scenario where we need to create a form within the dropdown menu to get some use
3 min read
How to create a Bootstrap panel with a heading ?
A panel is a rectangular component of Bootstrap, typically used to add content to the website. It can also have a header or footer, or both. Bootstrap also provides various classes to add padding to the content or multiple colors to make it more attractive. CDN Link: First, include the style sheet t
1 min read
How to Create Modal using Bootstrap?
Bootstrap modal box is a UI component that displays content overlaid on the main page. Create it by defining a trigger button with data attributes and structuring the modal in HTML with a unique ID, allowing customization of content and functionality. Syntax: <div class="modal"> Contents...
4 min read
How to create a Simple Footer using Bootstrap 5 ?
Bootstrap 5 Footers can be used for displaying Contact links, Social media links, Service links, Company Logos, and other sections. The <footer> tag can be used with built-in classes for making the responsive footer layout. For accomplishing this task, there are 2 approaches, i.e., by using Bo
4 min read
How to create full width container in bootstrap5?
Bootstrap containers are content holders that are used to align, add margins and padding to your content. Bootstrap has three different container classes, namely: .container .container-fluid .container-{breakpoint} Width of a container varies in accordance with its class. We can create a full width
1 min read