Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

Elevate User Experience with CSS Forms for Great Web Design

Forms are an integral part of any website, enabling users to interact with the site by providing their information. CSS (Cascading Style Sheets) is a powerful tool that used to style these forms, enhancing the user experience and making the website more visually appealing. In this article, we will delve into the world of CSS forms, exploring their structure, styling, responsiveness, advanced techniques, accessibility, cross-browser compatibility, best practices, and future trends.

If you’re working on a large or small web project requiring a lot of components, PureCode is your best bet. We’ve got over 1000+ AI-generated UI components, which will enable you to skip the tedious work of creating components yourself. Check PureCode out today.

Basics of Form Structure

You can create forms in HTML using a variety of elements. The <form> tag is the container for all form elements. It has several attributes, such as action, method, enctype, and target. These control how the form sends data to the server.

HTML Form Elements

  1. Input elements: These include text, password, checkbox, radio, etc. Each of these elements has different attributes and behaviors. For example, the type attribute specifies the type of input to display, such as text, password, checkbox, radio, etc.
  1. Select and option elements: These create a dropdown list. The <select> tag defines the dropdown list, and the <option> tag defines the available options in the list.
  1. Textarea element: This creates a multi-line text input field. It has two sizing attributes: cols for width in terms of the average character width and rows for height in terms of the number of lines of visible text.
  1. Button and submit elements: The <button> tag defines a clickable button. The <input> tag with type=”submit” creates a submit button.
  1. Fieldset and Legend elements: The <fieldset> element groups related elements in a form. The <legend> element defines a caption for the <fieldset> element. These elements are not mandatory but are very useful for more complex forms and for presentation.

Common Form Attributes

  • action: Specifies where to send the form-data during form submission.
  • method: Specifies the HTTP method (GET or POST) to use when sending form-data.
  • enctype: Specifies how the form-data should be encoded when submitting it to the server.
  • target: Specifies where to open the linked document.

In the next section, we will delve into how to style these form elements using CSS.

Basic CSS Form Styling

Styling forms with CSS can significantly enhance the user experience by making the forms visually appealing and intuitive to use. In this section, we will explore how to style form containers and form elements using CSS.

Styling Form Containers

The form container is the <form> element. It can be styled using properties like background, border, padding, margin, width, and height. For example, to give the form a light grey background, a border, and some padding, you can use the following CSS:

Background and Borders:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    form {
      background-color: #f4f4f4;
      border: 1px solid #ccc;
      padding: 20px;
      margin: 20px 0;
    }
  </style>
  <title>Styled Form Container</title>
</head>
<body>
  <form>
    <!-- Form elements go here -->
  </form>
</body>
</html>

This example sets a light background color, a subtle border, and provides some padding and margin to the form container.

Padding and Margin:

<style>
  form {
    padding: 20px;
    margin: 20px 0;
  }
</style>

Adjusting padding property and margin ensures proper spacing and a clean layout for the form.

Width and Height:

<style>
  form {
    width: 50%;
    max-width: 600px;
    margin: 0 auto;
  }
</style>

Setting the width ensures the form doesn’t span the entire width of the page, providing a more visually balanced appearance.

Here is the code combining all the properties discussed.

form {
    background: #f8f8f8;
    border: 1px solid #ccc;
    padding: 20px;
    margin: 20px 0;
    width: 50%;
    max-width: 600px;
}

If you prefer using premade templates for your forms component, check out PureCode’s library of over 10k components, including form and button components.

Start With PureCode

Styling Form Elements

Now, let’s focus on styling individual form elements to create a cohesive design.

Text Input Styling

We can style text input fields using properties like border, padding, margin, width, height, and font. For example, to give the text input fields a border, padding, and a specific font, you can use the following CSS:

input[type="text"] {
 border: 1px solid #ccc;
 padding: 10px;
 font: 1em/1.5em "Arial", sans-serif;
}

Checkbox and Radio Button Styling

Checkboxes and radio buttons can be styled using CSS, but it’s important to note that the default styling of these elements varies across different browsers. To achieve a consistent look, you can use custom controls, created using stylable HTML elements such as div and span.

input[type="checkbox"], input[type="radio"] {
  margin-right: 5px;
}

/* Optional: Add styles for checked state */
input[type="checkbox"]:checked, input[type="radio"]:checked {
  color: #fff;
  background-color: #3498db;
}

Select Box Styling

We can style select boxes using properties like border, padding, margin, width, height, and font. Here is an example of how to style select boxes:

select {
 border: 2px solid #333;
 background-color: white;
 border-radius: 0.25rem;
}

In this example, a 2px dark gray border is added around each of the data entry elements, along with a white background and rounded corners.

Textarea Styling

We can style Textarea fields using properties like border, padding, margin, width, height, and font. Here is an example of how to style textarea fields:

textarea {
 border: 1px solid #ccc;
 padding: 10px;
 font: 1em/1.5em "Arial", sans-serif;
}

In this example, a larger initial area for the form user to fill in text is created by setting a minimum height.

Button and Submit Styling

Buttons and submit fields can be styled using properties like border, padding, margin, width, height, background, color, font, and cursor. Here is an example of how to style buttons and submit fields:

button,
input[type="submit"] {
 background-color: purple;
 width: 180px;
 display: block;
 margin: 0px auto;
 border: none;
 border-radius: 5px;
 font-weight: bold;
 font-size: 18px;
 font-family: "Courier New", Courier, monospace;
 color: white;
 margin-top: 30px;
 padding: 20px;
 text-align: center;
 cursor: pointer;
}
input[type="submit"]:hover {
 background-color: indigo;
}

In this example, the submit button is styled with different CSS properties. The button changes color when hovered over.

Here is the complete code combining all the form elements discussed.

<!DOCTYPE html>
<html>
<head>
   <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
   <form>
       <label for="name">Name:</label><br>
       <input type="text" id="name" name="name"><br>
       <label for="email">Email:</label><br>
       <input type="email" id="email" name="email"><br>
       <label for="message">Message:</label><br>
       <textarea id="message" name="message"></textarea><br>
       <input type="checkbox" id="newsletter" name="newsletter">
       <label for="newsletter">Sign up for our newsletter</label><br>
       <input type="submit" value="Submit">
   </form>
</body>
</html>

Here is the CSS

body {
   margin: 0;
   background-color: hsl(0, 0%, 98%);
   color: #333;
   font: 100% / normal sans-serif;
}

form {
   box-sizing: border-box;
   padding: 2rem;
   border-radius: 1rem;
   background-color: hsl(0, 0%, 100%);
   border: 4px solid hsl(0, 0%, 90%);
   display: grid;
   grid-template-columns: 1fr 1fr;
   gap: 2rem;
}

input[type="text"],
input[type="email"],
select,
textarea {
   font: 1.25rem / 1.5 sans-serif;
   display: block;
   box-sizing: border-box;
   width: 100%;
   padding: 0.5rem 0.75rem;
   border: 2px solid #333;
   background-color: white;
   border-radius: 0.25rem;
}

textarea {
   min-height: 10rem;
}

button,
input[type="submit"] {
   background-color: purple;
   width: 180px;
   display: block;
   margin: 0px auto;
   border: none;
   border-radius: 5px;
   font-weight: bold;
   font-size: 18px;
   font-family: "Courier New", Courier, monospace;
   color: white;
   margin-top: 30px;
   padding: 20px;
   text-align: center;
   cursor: pointer;
}

input[type="submit"]:hover {
   background-color: indigo;
}

Responsive Design for Forms

Responsive design is about creating web pages that look good on all devices. A responsive web design will automatically adjust for different screen sizes and viewports. In the context of forms, this means ensuring that the form layout and elements adapt to different screen sizes, providing a consistent user experience across all devices.

Media Queries for Form Layout

Media queries are a feature of CSS that allow you to apply different styles depending on the characteristics of the device display, such as its width or height. For example, you can use a media query to change the layout of the form when the screen width is less than 600px, making the form elements stack vertically instead of horizontally.

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style>
        form {
            width: 50%;
            max-width: 600px;
            margin: 0 auto;
        }
    
        @media (max-width: 600px) {
            form {
                width: 80%;
            }
        }
    </style>
</head>

<body>
    <form>
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name"><br>
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email"><br>
        <label for="message">Message:</label><br>
        <textarea id="message" name="message"></textarea><br>
        <input type="checkbox" id="newsletter" name="newsletter">
        <label for="newsletter">Sign up for our newsletter</label><br>
        <button>Submit</button>
    </form>
</body>

</html>

Flexbox and Grid for Responsive Forms

Flexbox and Grid are CSS layout modules that create responsive forms. The former allows you to design a flexible responsive layout structure without using float or positioning. Grid, on the other hand, is a 2-dimensional system that can handle both columns and rows. It can be used to create complex responsive layouts.

Responsive form with Flexbox:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Form</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background-color: #f4f4f4;
        }

        form {
            width: 300px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
        }

        label {
            margin-bottom: 8px;
            font-weight: bold;
        }

        input {
            padding: 10px;
            margin-bottom: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px;
            background-color: #4caf50;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #45a049;
        }

        @media screen and (max-width: 600px) {
            form {
                width: 80%;
            }
        }
    </style>
</head>

<body>

    <form>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>

        <button type="submit">Submit</button>
    </form>

</body>

</html>

Responsive form with Grid:


        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background-color: #f4f4f4;
        }

        form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            grid-gap: 16px;
            max-width: 600px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        label {
            grid-column: span 2;
            margin-bottom: 8px;
            font-weight: bold;
        }

        input {
            width: 100%;
            padding: 10px;
            margin-bottom: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            grid-column: span 2;
            padding: 10px;
            background-color: #4caf50;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #45a049;
        }

        @media screen and (max-width: 600px) {
            form {
                grid-template-columns: 1fr;
            }
        }

Fluid Width Forms

Fluid width forms take up the full width of the screen, regardless of the screen size. This ensures that the form looks good on all devices, from large desktop monitors to small mobile screens. To create a fluid width form, you can set the width of the form and its elements to a percentage value, rather than a fixed pixel value.


        form {
            max-width: 100%;
            width: 80%;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        label {
            margin-bottom: 8px;
            font-weight: bold;
        }

        input {
            width: 100%;
            box-sizing: border-box;
            padding: 10px;
            margin-bottom: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            width: 100%;
            padding: 10px;
            background-color: #4caf50;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #45a049;
        }

In this example, the form has a maximum width of 100% and a fluid width of 80%, making it responsive to different screen sizes. The input fields and the submit button also have a width of 100%, allowing them to adapt to the width of the form container. The styling provides a clean and adaptable design.

Advanced CSS Techniques

Advanced CSS techniques allow developers to create more complex, interactive, and visually appealing designs. These techniques enhance the user experience, making websites more engaging and easier to use. In this section, we will explore some of the advanced CSS techniques, including pseudo-classes and pseudo-elements, transitions and animations, and using custom form styling libraries.

Pseudo-classes and Pseudo-elements

Pseudo-classes and pseudo-elements are advanced CSS selectors that allow you to style elements based on their state or position in the document. For example, the :hover pseudo-class changes the style of an element when the user hovers over it. The ::before and ::after pseudo-elements insert content before or after an element.

Here is an example of using pseudo-classes and pseudo-elements in a form:

input[type="text"]:focus::before {
 content: "Enter your name";
 color: #888;
}

input[type="text"]:focus {
 border-color: #007BFF;
}

In this example, the ::before pseudo-element displays a placeholder text with a focused text input field. The :focus pseudo-class changes the border color of the text input field when it is focused.

Transitions and Animations

Transitions and animations are powerful CSS features that allow you to create smooth, interactive effects. Firstly, transitions allow you to change property values smoothly over a given duration. Animations, on the other hand, allow you to create complex animations by defining keyframes.

Here is an example of using transitions and animations in a form:

input[type="submit"] {
 transition: background-color 0.3s ease;
}

input[type="submit"]:hover {
 background-color: #0056b3;
}

@keyframes shake {
 0%, 100% {
  transform: translateX(0);
 }
 10%, 30%, 50%, 70%, 90% {
  transform: translateX(-10px);
 }
 20%, 40%, 60%, 80% {
  transform: translateX(10px);
 }
}

input[type="submit"]:active {
 animation: shake 0.5s;
}

In this example, the transition property is used to change the background color of the submit button smoothly over 0.3 seconds when it is hovered over. The @keyframes rule is used to define a shake animation, which is applied to the submit button when it is active.

Custom Form Styling Libraries

There are several libraries available that provide pre-styled form elements, such as Bootstrap and Tailwind CSS. These libraries can save you time and ensure consistency across your forms. They provide a wide range of pre-styled form elements, including buttons, input fields, checkboxes, radio buttons, and more .

Here is an example of using Bootstrap to style a form:

<!DOCTYPE html>
<html>
<head>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
 <form>
  <div class="form-group">
    <label for="name">Name:</label>
    <input type="text" class="form-control" id="name">
  </div>
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" id="email">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
 </form>
</body>
</html>

In this example, the form-group class is used to wrap each form element and label, and the form-control class is used to style the input fields. The btn and btn-primary classes are used to style the submit button

Accessibility in CSS Web Forms

Accessibility is a crucial aspect of web design. It ensures that your website is usable by everyone, including users with disabilities. This section will cover some of the best practices and techniques for creating accessible forms using CSS.

Semantic HTML Elements

Using the appropriate HTML forms elements for the right purpose is important to ensure accessibility. For example, using a <div> with a click event instead of a <button> element will make it difficult for screen readers to understand the purpose of that element. The <form>, <input>, <label>, <select>, and <textarea> are some of the most commonly used elements in forms.

ARIA Attributes

ARIA (Accessible Rich Internet Applications) attributes can provide additional information about form controls and improve accessibility. The aria-label, aria-describedby, and aria-required attributes are examples of ARIA attributes that can enhance the accessibility of forms.

Labeling Controls

The <label> element is used to associate form controls with their labels. This is important for screen readers to understand the purpose of each form control. For example:

<label for="name">Name:</label>
<input type="text" id="name" name="name">

In this example, the for attribute of the <label> element is used to associate the label with the input field.

Grouping Controls

The <fieldset> and <legend> elements are used to group and associate related form controls. This will help users to understand the relationship between different form controls and make it easier to navigate through the form.

Styling Form Controls

CSS can be used to style form controls such as text inputs, radio buttons, and checkboxes. For example, using CSS to add a background color and border to form controls will make it easier for users to understand the purpose of each form control.

input[type="text"],
input[type="email"],
select,
textarea {
 font: 1.25rem / 1.5 sans-serif;
 display: block;
 box-sizing: border-box;
 width: 100%;
 padding: 0.5rem 0.75rem;
 border: 2px solid #333;
 background-color: white;
 border-radius: 0.25rem;
}

In this example, a 2px dark gray border is added around each of the data entry elements, along with a white background and rounded corners.

Form Instructions

Providing instructions to help users understand how to complete the form and individual form controls is a crucial part of accessibility. This can be achieved using the <p> tag or the placeholder attribute in input fields.

<p>Please fill out the form below:</p>
<form>
 <label for="name">Name:</label>
 <input type="text" id="name" name="name" placeholder="Enter your name">
 <label for="email">Email:</label>
 <input type="email" id="email" name="email" placeholder="Enter your email">
 <input type="submit" value="Submit">
</form>

In this example, a paragraph is used to provide instructions, and the placeholder attribute is used to provide instructions for each input field.

User Notifications

Notify users about successful task completion, any errors, and provide instructions to help them correct mistakes. This can be achieved using the <p> tag or the alert role in ARIA.

<p role="alert">Your form has been submitted successfully.</p>

In this example, the role attribute is used to indicate that the paragraph is used for alerts.

Custom Controls

Use stylized form elements and other progressive enhancement techniques to provide custom controls. This can be achieved using CSS and JavaScript.

In conclusion, creating accessible and responsive forms is crucial for ensuring that all users can use and understand your forms. By following the best practices and techniques outlined in this guide, you can create forms that are easy to use and understand for all users, regardless of their abilities or the devices they are using.

Best Practices for CSS Form Design

No.Best PracticeDescription
1Consistent DesignMaintain a cohesive design across all form elements to create a unified and visually pleasing user interface.
2User-Friendly FeedbackProvide clear and helpful feedback to users, especially during form submission and validation processes.
3Error Handling and ValidationImplement robust error handling and validation mechanisms to guide users and ensure data accuracy.
4AccessibilityPrioritize accessibility by using ARIA roles, ensuring sufficient contrast, and providing clear labels for screen readers.
5Cross-Browser CompatibilityTest and optimize your forms for compatibility across various browsers to ensure a consistent experience for all users.
6Responsive DesignUtilize responsive design principles, media queries, and flexible layouts to adapt forms to different screen sizes and devices.
7Pseudo-classes and Pseudo-elementsLeverage pseudo-classes and pseudo-elements for enhanced styling and interactive effects, such as hover and focus states.
9Custom Form Styling LibrariesExplore and integrate custom styling libraries like Bootstrap or Tailwind CSS for efficient and consistent form designs.
8Transitions and AnimationsEmploy transitions and animations judiciously to create smooth interactions and provide visual cues for users.

Endnote

Mastering CSS forms for web design is a journey that requires a deep understanding of CSS properties, techniques, and best practices. It’s about creating forms that not only look good but also provide a seamless user experience.

From understanding the basics of form design principles, such as hierarchy, contrast, repetition, alignment, and proximity, to leveraging advanced CSS techniques like Flexbox and Grid for responsive design, and using pseudo-classes and pseudo-elements for interactive effects, CSS forms can be elevated to a whole new level.

In conclusion, CSS forms are a powerful tool for web design. With the right techniques and practices, you can create forms that are visually appealing, responsive, accessible, and provide a seamless user experience. So, let’s keep exploring and mastering CSS forms to elevate our web designs.

If you’d like to speed up your development time, we recommend checking out PureCode. PureCode allows you to add custom themes to your projects built using CSS3, Tailwind CSS, or Material UI. Check our marketplace; choose from over 10,000 AI-generated custom components.

Further Reading:

To learn more about building responsive websites, check out the following tutorials.

Also check out the video below to learn more advanced ways to style form in CSS. Happy coding!

Victor Yakubu

Victor Yakubu