Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using Labels for Better Form Accessibility | HTML Forms and User Input
Ultimate HTML
course content

Course Content

Ultimate HTML

Ultimate HTML

1. Understanding Web Development
2. HTML Tags and Attributes
3. HTML Document Structure
4. Working with Media and Tables
5. HTML Forms and User Input

book
Using Labels for Better Form Accessibility

The <label> element is used to associate a label with an input field on a form. This association helps users understand the information being requested in the form field. When a user clicks on the label, it automatically focuses on the corresponding input field.

There are two ways to connect label and input elements:

Wrapping

By nesting a form element, such as an <input/> field, within a <label> element, the browser automatically establishes a link between the label and the input field. For example:

html

index.html

copy

In this example, clicking on the label text "Name" will automatically focus on the corresponding input field.

Using the id Attribute

When a form element is not nested within a <label> element, you manually link them by using the id attribute of the input element and the for attribute of the label. The value of the for attribute and id attribute must be the same. For example:

html

index.html

copy

In this case, the label is associated with the input field using the for attribute on the label and the id attribute on the input field. Clicking on the label text "Name" will also focus on the corresponding input field.

Note

Using these methods, you establish a visual and semantic connection between the label and the input field. However, there may be situations where wrapping the input element within the label is impossible due to styling constraints or website logic. In such cases, you commonly rely on attribute connections to maintain flexibility in applying styles and implementing background logic.

Let's examine the difference between the two approaches by examining the code in the image.

Note

From the browser's perspective, the chosen approach to establish the connection is inconsequential. Both methods achieve the same result of linking the label and input field together for improved usability and accessibility.

question mark

What is the purpose of the <label> element in HTML forms?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt