Lesson · HTML & CSS Basics
Forms and labels
Forms let people provide information, so each control needs a clear purpose and label.
What you will learn
- Associate labels with form controls
- Choose a suitable input type
- Use button text that explains the action
Give controls a name
A label element should be programmatically associated with its input. The for attribute on a label matches the id of the control. Clicking the label then focuses the control, and assistive technology can announce the prompt with the input. Placeholder text is not a replacement for a persistent label.
Choose a fitting control
Use a text input for short free-form text, an email input when an email address is expected, and a textarea for longer text. Input types can provide helpful browser behavior, but the server must still validate submitted data. Required attributes and client-side checks improve guidance but cannot make untrusted input safe by themselves.
Make the action clear
A submit button should describe what happens, such as 'Send question'. If a form has multiple buttons, choose explicit types so a secondary control does not accidentally submit the form. A form's action and method should match the receiving application; a static example can demonstrate structure without pretending to send data.
Think beyond the happy path
Users may have keyboard-only navigation, magnification, or an assistive technology. Keep labels visible, group related controls, and make errors explain what needs correction. Do not rely on color alone to identify a required field or communicate an error.
Make returning to a form easier
Attributes such as autocomplete can help a browser fill common fields when that is appropriate. Group related controls with fieldset and legend when the form has a meaningful group. A validation message should identify the field and describe how to correct it; a red border without an explanation does not tell a person what to change.
<form action="/contact/" method="post">
<label for="topic">Question topic</label>
<input id="topic" name="topic" type="text" required>
<label for="email">Email address</label>
<input id="email" name="email" type="email" required>
<button type="submit">Send question</button>
</form>
Practice exercise
Create a form with a labelled email field and a submit button that says what it will do.
Show a hint
Match each label's for value to its input id.
Show one possible solution
Create a label with for='email', an input with id='email' and type='email', and a submit button with clear action text.
Quick check
The matching identifiers create an explicit label-control association.