Формы

Label html text value

Существует два способа связывания объекта и метки. Первый заключается в использовании идентификатора id внутри элемента формы и указании его имени в качестве атрибута for элемента . При втором способе элемент формы помещается внутрь контейнера .

Синтаксис

Атрибуты

Также для этого элемента доступны универсальные атрибуты и события.

Пример

Примечание

IE до версии 6.0 включительно не позволяет активировать поле формы при щелчке по тексту, когда поле с текстом находится внутри .

IE до версии 8.0 включительно корректно работает с только при наличии в нём текста. Если добавить изображение ( ), то активировать поле формы щелчком по картинке нельзя.

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.
Читайте также:  What is php nuke

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

См. также

  • Аккордеон меню
  • Вкладки на CSS
  • Выпадающее меню
  • Использование :checked
  • Подсказка в поле формы
  • Пользовательские формы
  • Стилизация переключателей
  • Стилизация флажков
  • Формы в Bootstrap 4
  • Формы в HTML
  • Элемент label

Источник

HTML Tag

The tag is also used to define keyboard shortcuts and jump to the active element like links.

An input can be associated with several labels. If you click or tap a which is associated with a form control, the resulting click event will arise for the associated control.

Associating a with an element has some advantages:

  • The label text is both visually and pragmatically associated with the text input.
  • You can click on the associated label for focusing or activating the input, as well as on the input itself.

Syntax

The

There are two ways to associate a text label and the form to which it belongs:

Example of the HTML tag:

html> html> head> title>Title of the document title> head> body> form> label for="lfname">First name: label> input id="lfname" name="fname" type="text" /> form> body> html>

Result

simple label exmample

Example of the HTML tag with an element inside:

html> html> head> title>Title of the document title> head> body> form> label>Name input id="User" name="Name" type="text" /> label> form> body> html>

Example of HTML with a tag used with radio type of an tag:

html> html> head> title>Title of the document title> head> body> form> label for="barca">Barcelona label> input type="radio" name="team" id="barca" value="Barcelona"> br /> label for="real">Real Madrid label> input type="radio" name="team" id="real" value="Real Madrid"> br /> form> body> html>

Example of the HTML tag with CSS font properties:

html> html> head> title>Title of the document title> style> body < padding: 20px; > label < font-size: 20px; font-weight: 700; color: #1c87c9; > input < width: 50%; height: 28px; padding: 4px 10px; border: 1px solid #666; background: #cce6ff; color: #1c87c9; font-size: 16px; > style> head> body> form> label>Your Name: label> input id="User" name="Name" type="text"/> form> body> html>

Attributes

Attribute Value Description
accesskey accesskey Defines a hot key with which you can go to the attached to the label (through a for attribute) form element.
for element_id Sets the ID of the element to which the label should be bound.
form form_id Specifies the form (s) with which the label will be associated. This attribute allows you to place tags in an arbitrary location in the document, and not just as a descendant of the element. Obsolete.

How to style tag?

Common properties to alter the visual weight/emphasis/size of text in tag:

  • CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
  • CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
  • CSS font-size property sets the size of the font.
  • CSS font-weight property defines whether the font should be bold or thick.
  • CSS text-transform property controls text case and capitalization.
  • CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.

Coloring text in tag:

  • CSS color property describes the color of the text content and text decorations.
  • CSS background-color property sets the background color of an element.

Text layout styles for tag:

  • CSS text-indent property specifies the indentation of the first line in a text block.
  • CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
  • CSS white-space property specifies how white-space inside an element is handled.
  • CSS word-break property specifies where the lines should be broken.

Other properties worth looking at for tag:

  • CSS text-shadow property adds shadow to text.
  • CSS text-align-last property sets the alignment of the last line of the text.
  • CSS line-height property specifies the height of a line.
  • CSS letter-spacing property defines the spaces between letters/characters in a text.
  • CSS word-spacing property sets the spacing between words.

Источник

: 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> 

Источник

Элемент label

Элемент связывает текст с определённым элементом формы. Обычно применяется в следующих случаях.

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

Простой вариант использования заключается в добавлении полей формы прямо внутрь с желаемым текстом, как показано в примере 1.

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

Поля формы и текст для них могут визуально находиться рядом, но в коде документа располагаться внутри разных элементов. Чтобы связать их между собой применяется атрибут for , его значением выступает идентификатор у , как показано в примере 2.

# Работа со временем

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

Также применяется как один из элементов для вёрстки сложных форм. В примере 3 показана форма авторизации, в которой текст располагается рядом с полями для ввода логина и пароля.

Пример 3. Форма для авторизации

Результат данного примера показан на рис. 1.

Форма для авторизации пользователя

Рис. 1. Форма для авторизации пользователя

См. также

  • Аккордеон меню
  • Вкладки на CSS
  • Выпадающее меню
  • Использование :checked
  • Подсказка в поле формы
  • Пользовательские формы
  • Стилизация переключателей
  • Стилизация флажков
  • Формы в Bootstrap 4
  • Формы в HTML

Источник

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