Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Label for Input Element | Forms
Ultimate HTML
course content

Course Content

Ultimate HTML

Ultimate HTML

1. Web Development
2. Tags and Attributes
3. Document Structure
4. Media and Tables
5. Forms

bookLabel for Input Element

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

css

index

js

index

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, we 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

css

index

js

index

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, we 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, we 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.

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