CSS ยท Chapter 39 of 44

CSS Forms

CSS can style form elements like inputs, textareas, and buttons for a consistent, polished look, including focus states and validation feedback.

Common techniques include styling :focus for active fields, and using :valid/:invalid to give visual feedback based on input validity.

Syntax
input:focus { }
input:invalid { }

Styling inputs and buttons

You can style padding, border, border-radius, and background on inputs and buttons just like any other element, creating a consistent design system.

Focus and validation states

:focus highlights the active field. :valid and :invalid style inputs based on whether their value passes validation, giving users immediate feedback.

Example 1 (css)
input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
input:focus {
  border-color: #264de4;
  outline: none;
}
Output
Inputs have rounded, padded borders, turning blue when focused

The :focus state changes the border color to give clear visual feedback when typing.

Key points

  • Form elements can be styled like any other element.
  • :focus highlights the currently active input.
  • :valid and :invalid style inputs based on validation state.
  • Consistent form styling improves usability and trust.
๐Ÿ’ก Note: Removing the default outline with outline: none should be paired with another visible focus style for accessibility.

๐Ÿ“ Quick Quiz

1. Which pseudo-class targets the currently active input field?

2. Which pseudo-class styles inputs that fail validation?

3. Why should outline: none be paired with another focus style?