Forms play a crucial role in web development, whether it’s for gathering user feedback, collecting personal information or facilitating a payment transaction.
In this tutorial, we will walk you through the process of creating a responsive form using CSS.
A responsive form adjusts to the size of the device it’s viewed on, providing an optimal user experience.
Getting Started
Before we dive into the coding aspect, let’s first identify the key components of a form.
A form typically consists of the following elements:
- Input fields (text, email, password, etc.)
- Labels
- Buttons (submit, reset, etc.)
Now that we know what makes up a form, let’s start coding.
Step 1: HTML Markup
The first step in creating a responsive form is to write the HTML markup.
Below is an example of a simple form with input fields, labels and a submit button.
<form> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="email">Email:</label> <input type="email" id="email" name="email"> <label for="password">Password:</label> <input type="password" id="password" name="password"> <input type="submit" value="Submit"> </form>
Step 2: Add CSS Styles
Once the HTML markup is complete, we can start adding the styles. We will use CSS media queries to make the form responsive.
Media queries are CSS statements that allow us to apply styles based on the size of the viewport.
Here is an example of a CSS stylesheet for a responsive form.
form { width: 80%%; margin: 0 auto; text-align: center; } label, input[type="text"], input[type="email"], input[type="password"] { width: 100%%; padding: 12px; margin-bottom: 20px; box-sizing: border-box; border: 2px solid #ccc; border-radius: 4px; } input[type="submit"] { width: 100%%; padding: 12px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; } @media screen and (max-width: 600px) { form { width: 100%%; } }
Step 3: Test the Form
Now that the form is complete, it’s time to test it on different devices.
Resize the browser window to check that the form adjusts to the size of the viewport.
Conclusion
In this article, we walked you through the process of creating a responsive form using CSS.
By using media queries, we were able to adjust the form’s size based on the size of the viewport, providing an optimal user experience.