Тег позволяет создать элемент интерфейса в виде раскрывающегося списка, а также список с одним или множественным выбором, как показано далее. Конечный вид зависит от использования атрибута size тега , который устанавливает высоту списка. Ширина списка определяется самым широким текстом, указанным в теге , а также может изменяться с помощью стилей. Каждый пункт создается с помощью тега , который должен быть вложен в контейнер . Если планируется отправлять данные списка на сервер, то требуется поместить элемент внутрь формы. Это также необходимо, когда к данным списка идет обращение через скрипты.
Список множественного выбора
Раскрывающийся список
Синтаксис
Атрибуты
accesskey Позволяет перейти к списку с помощью некоторого сочетания клавиш. autofocus Устанавливает, что список получает фокус после загрузки страницы. disabled Блокирует доступ и изменение элемента. form Связывает список с формой. multiple Позволяет одновременно выбирать сразу несколько элементов списка. name Имя элемента для отправки на сервер или обращения через скрипты. required Список обязателен для выбора перед отправкой формы. size Количество отображаемых строк списка. tabindex Определяет последовательность перехода между элементами при нажатии на клавишу Tab
Также для этого тега доступны универсальные атрибуты и события.
HTML tag is used to create drop down list of options, which appears when the user clicks on form element, and it allows to choose one of the options.
The first option from the list of options is selected by default. To change a predefined option, the selected attribute is used.
The list appearance depends on the size attribute, which specifies the height of the list. The width of the list depends on the length of the text inside . The width can also be regulated with CSS styles.
The tag is difficult to style effectively with CSS. You can affect certain parts of an element. For example, it’s possible to control the displayed font, box model, etc., as well as you can use the appearance property for removing the default system appearance. But these properties do not give a stable result across browsers. The internal structure of the tag is complicated, and it is difficult to control. For getting a full control, you may need a library with better styling form widgets, or a dropdown menu using non-semantic elements.
If you need to send the data to the server or refer to the list with scripts, the
html> html> head> title>Window title of the page title> head> body> selectaria-label="Books nad Snippets"> optgrouplabel="Books"> optionvalue="html">HTML option> optionvalue="css">CSS option> optgroup> optgrouplabel="Snippets"> optionvalue="git">Git option> optionvalue="java">Java option> optgroup> select> body> html>
In this example, the tag is used to collect the options into groups.
Result
Example of the HTML tag with the tag:
html> html> head> title>Window title of the page title> head> body> p>Airport of departure: p> formaction="action_form.php"method="get"> inputtype="text"list="airports"name="airports"> datalistid="airports"> optionvalue="Berlin"> optionvalue="Los Angeles"> optionvalue="Moscow"> optionvalue="Paris"> datalist> inputtype="submit"value="confirm"> form> body> html>
In this example, the tag is used because we need to send information to the server.
Result
Attributes
Attribute
Value
Description
autofocus
autofocus
Defines that the list should be focused after the page loads.
disabled
disabled
Indicates that the list is disabled, the user cannot interact with it.
form
form_id
Defines the form which the element is connected with. Is not supported in Firefox.
multiple:
multiple:
Indicates that more than one options can be chosen. The method of choosing more than one option depends on the operating system. In Windows, you need to keep CTRL button pressed, in Mac CMD button.
name
name
Defines a name for the drop down menu. It can be used to access the data of the form after it has been sent or to link to JavaScript element.
required
required
Indicated that the the choice of an option is required.
size
number
Indicated the count of the options in drop down list. If the value of «size» attribute is bigger than 1 and smaller than the total number of the options in the list, the browser will automatically add a scroll to indicate that there are more options to view.
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.
Тег позволяет создать элемент интерфейса в виде раскрывающегося списка, а также список с одним или множественным выбором, как показано далее. Конечный вид зависит от использования атрибута size тега , который устанавливает высоту списка. Ширина списка определяется самым широким текстом, указанным в теге , а также может изменяться с помощью стилей. Каждый пункт создается с помощью тега , который должен быть вложен в контейнер . Если планируется отправлять данные списка на сервер, то требуется поместить элемент внутрь формы. Это также необходимо, когда к данным списка идет обращение через скрипты.
Список множественного выбора
Раскрывающийся список
Синтаксис
Атрибуты
accesskey Позволяет перейти к списку с помощью некоторого сочетания клавиш. autofocus Устанавливает, что список получает фокус после загрузки страницы. disabled Блокирует доступ и изменение элемента. form Связывает список с формой. multiple Позволяет одновременно выбирать сразу несколько элементов списка. name Имя элемента для отправки на сервер или обращения через скрипты. required Список обязателен для выбора перед отправкой формы. size Количество отображаемых строк списка. tabindex Определяет последовательность перехода между элементами при нажатии на клавишу Tab
Также для этого тега доступны универсальные атрибуты и события.