What is label in html form

: The Input Label element

The HTML element represents a caption for an item in a user interface.

Try it

  • The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
  • When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device.

To associate the with an element, you need to give the an id attribute. The then needs a for attribute whose value is the same as the input’s id .

Alternatively, you can nest the directly inside the , in which case the for and id attributes are not needed because the association is implicit:

label>Do you like peas? input type="checkbox" name="peas"> label> 

The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:

label for="username">Enter your username: label> input id="username"> label for="username">Forgot your username? label> 

Elements that can be associated with a element include , (except for type=»hidden» ), , , , and .

Attributes

This element includes the global attributes.

The value of the for attribute must be a single id for a labelable form-related element in the same document as the element. So, any given label element can be associated with only one form control.

Note: To programmatically set the for attribute, use htmlFor .

The first element in the document with an id attribute matching the value of the for attribute is the labeled control for this label element — if the element with that id is actually a labelable element. If it is not a labelable element, then the for attribute has no effect. If there are other elements that also match the id value, later in the document, they are not considered.

Multiple label elements can be given the same value for their for attribute; doing so causes the associated form control (the form control that for value references) to have multiple labels.

Читайте также:  Python convert utf to unicode

Note: A element can have both a for attribute and a contained control element, as long as the for attribute points to the contained control element.

Styling with CSS

There are no special styling considerations for elements — structurally they are simple inline elements, and so can be styled in much the same way as a or element. You can apply styling to them in any way you want, as long as you don’t cause the text to become difficult to read.

Examples

Simple label example

label>Click me input type="text"> label> 

Источник

What is label in html form

Подписывает поля ввода и другие элементы формы.

Время чтения: меньше 5 мин

Обновлено 8 сентября 2022

Кратко

Скопировать ссылку «Кратко» Скопировано

Элемент используется для создания подписи к элементу формы:

Пример

Скопировать ссылку «Пример» Скопировано

     div class="form-row"> label for="bread">Купить хлебlabel> input type="checkbox" name="bread" id="bread"> div>      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 ) -->  ) --> label>Click me input type="text">label> label for="username">Click melabel> input type="text" id="username">      

Как понять

Скопировать ссылку "Как понять" Скопировано

На многих веб-страницах есть формы — группы интерактивных элементов (полей ввода, выпадающих списков, чекбоксов и т.п.), связанных общим функциональным назначением. Яркие примеры форм — форма регистрации, форма входа, фильтры в каталогах. Формами удобно пользоваться, когда мы понимаем назначение каждого элемента. Для этого необходимо подписывать каждый элемент. И вот как раз для этих целей служит элемент .

Помимо текстовой подписи создаётся программная связь между подписью и элементом формы. Это сильно облегчает взаимодействие с формами незрячим или слабовидящим пользователям, использующим скринридеры. Когда фокус попадает на элемент формы, с которым связан , скринридер автоматически зачитывает текст подписи, и пользователь понимает, какие данные необходимо ввести или какие данные представлены в текущем элементе формы.

Чтобы связать с элементом формы можно пойти двумя путями:

  1. Задаём элементу формы атрибут id . Такое же значение задаём атрибуту for тега .
  2. Оборачиваем элемент формы в тег . В этом случае связь создаётся автоматически и нет необходимости в атрибутах id и for .
      Согласен на обработку данных   form action=""> label for="phone">Ваш телефон:label> input type="tel" name="phone" id="phone"> label> input type="checkbox" name="agree">Согласен на обработку данных label> form>      

Атрибуты

Скопировать ссылку "Атрибуты" Скопировано

for — значение этого атрибута должно соответствовать значению атрибута id связываемого элемента. Первый же элемент в документе, чей id будет совпадать со значением атрибута for , становится связанным с нашим . Единственное условие — элемент должен принадлежать к группе связываемых элементов: , , , , , и .

Если элемент с нужным id не является связываемым, то связь не создаётся, и даже если дальше по документу найдётся связываемый элемент с таким же id , то он уже не будет учитываться.

Подсказки

Скопировать ссылку "Подсказки" Скопировано

💡 Один элемент формы может быть связан с несколькими , но один может быть связан ровно с одним элементом формы.

💡 При клике на событие клика вызывается также и на связанном элементе формы.

💡 По умолчанию является строчным элементом и стилизуется аналогично или .

На практике

Скопировать ссылку "На практике" Скопировано

Денис Ежков советует

Скопировать ссылку "Денис Ежков советует" Скопировано

🛠 Обязательно связывайте с чекбоксами и радиокнопками. Это небольшие элементы интерфейса, в которые довольно сложно попасть курсором мыши или пальцем на мобильных устройствах. Если у них есть связанный , то пользователь может кликать по тексту подписи, а не целиться в сам чекбокс. Любите своих пользователей! 😉

Алёна Батицкая советует

Скопировать ссылку "Алёна Батицкая советует" Скопировано

🛠 Даже если дизайнер нарисовал форму, в которой не предусмотрены явные лейблы для элементов, то вам нужно всё равно прописать их в разметке и скрыть через стили. В этом случае их будет не видно, но скринридер их прочитает.

🛠 При нажатии на лейбл, связанный с полем ввода или другим элементом формы, фокус будет перемещён на этот элемент.

На собеседовании

Скопировать ссылку "На собеседовании" Скопировано

Какая разница между legend , caption и label с точки зрения доступности? Что между ними общего?

Скопировать ссылку "Какая разница между legend, caption и label с точки зрения доступности? Что между ними общего?" Скопировано

Это вопрос без ответа. Вы можете помочь! Почитайте о том, как контрибьютить в Доку.

Источник

: The Label element

The HTML element represents a caption for an item in a user interface.

Try it

Associating a with a form control, such as or offers some major advantages:

  • The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
  • When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device.

To explicitly associate a element with an element, you first need to add the id attribute to the element. Next, you add the for attribute to the element, where the value of for is the same as the id in the element.

Alternatively, you can nest the directly inside the , in which case the for and id attributes are not needed because the association is implicit:

label> Do you like peas? input type="checkbox" name="peas" /> label> 

The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:

label for="username">Enter your username:label> input id="username" name="username" type="text" /> label for="username">Forgot your username?label> 

Elements that can be associated with a element include , (except for type="hidden" ), , , , and .

Attributes

This element includes the global attributes.

The value of the for attribute must be a single id for a labelable form-related element in the same document as the element. So, any given label element can be associated with only one form control.

Note: To programmatically set the for attribute, use htmlFor .

The first element in the document with an id attribute matching the value of the for attribute is the labeled control for this label element — if the element with that id is actually a labelable element. If it is not a labelable element, then the for attribute has no effect. If there are other elements that also match the id value, later in the document, they are not considered.

Multiple label elements can be given the same value for their for attribute; doing so causes the associated form control (the form control that for value references) to have multiple labels.

Note: A element can have both a for attribute and a contained control element, as long as the for attribute points to the contained control element.

Styling with CSS

There are no special styling considerations for elements — structurally they are simple inline elements, and so can be styled in much the same way as a or element. You can apply styling to them in any way you want, as long as you don't cause the text to become difficult to read.

Examples

Defining an implicit label

label>Click me input type="text" />label> 

Источник

Оцените статью