HTML <label> Element

Publish in HTML Tutorial el 24/05/2025 16:11

The <label> element is a crucial HTML tag that improves form accessibility and usability. It creates a caption for form elements like inputs, textareas, selects, etc. When properly associated with a form control, clicking the label focuses or activates the control, making the interface more user-friendly.


Key features of <label>:

  • Enhances accessibility for screen readers
  • Increases clickable area for form controls
  • Improves form organization and semantics
  • Can be associated with controls using either the "for" attribute or by nesting


Basic Syntax

Here's the basic structure of a label element:


Examples

1. Basic Label with Input

The most common use case - associating a label with a text input.

Play Code


2. Nested Label

Alternative method where the input is nested inside the label (no "for" attribute needed).

Play Code


3. Label with Radio Buttons

Using labels with radio buttons creates a more accessible radio group.

Play Code


4. Label with JavaScript (Focus)

This example shows how to use JavaScript to focus an input when its label is clicked.

Play Code


5. Label with JavaScript (Toggle Visibility)

This example demonstrates using JavaScript to toggle visibility of an input when clicking its label.

Play Code


Tips and Tricks

  • Always use labels: Every form control should have an associated label.
  • Use "for" attribute: Explicit association is often clearer than nesting.
  • Style consistently: Use CSS to make your labels visually consistent.
  • Keep labels concise: Labels should be short but descriptive.
  • Consider placeholder text: Placeholders can supplement but not replace labels.


Accessibility Considerations

Labels are essential for accessibility:

  • Screen readers use labels to announce form controls
  • Labels provide context for users with cognitive disabilities
  • Proper labeling helps users understand what information is expected
  • Clickable labels benefit users with motor control difficulties

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <source> Element
HTML <source> Element

The <source> element is used to specify multiple media resources for media elements like &l...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...