From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- files/uk/web/html/attributes/index.html | 654 ++++++++++++++++++ files/uk/web/html/block-level_elements/index.html | 133 ++++ files/uk/web/html/element/input/date/index.html | 510 ++++++++++++++ .../html/element/input/datetime-local/index.html | 543 +++++++++++++++ files/uk/web/html/element/input/index.html | 753 +++++++++++++++++++++ files/uk/web/html/index.html | 91 +++ files/uk/web/html/inline_elements/index.html | 79 +++ .../index.html" | 27 + .../html/index.html" | 169 +++++ .../iframe/index.html" | 260 +++++++ .../index.html" | 96 +++ .../link/index.html" | 325 +++++++++ .../nav/index.html" | 99 +++ .../script/index.html" | 243 +++++++ .../section/index.html" | 173 +++++ .../style/index.html" | 201 ++++++ .../table/index.html" | 371 ++++++++++ .../video/index.html" | 420 ++++++++++++ .../index.html" | 145 ++++ .../hidden/index.html" | 68 ++ .../index.html" | 474 +++++++++++++ .../itemscope/index.html" | 319 +++++++++ .../lang/index.html" | 90 +++ .../tabindex/index.html" | 96 +++ .../index.html" | 46 ++ 25 files changed, 6385 insertions(+) create mode 100644 files/uk/web/html/attributes/index.html create mode 100644 files/uk/web/html/block-level_elements/index.html create mode 100644 files/uk/web/html/element/input/date/index.html create mode 100644 files/uk/web/html/element/input/datetime-local/index.html create mode 100644 files/uk/web/html/element/input/index.html create mode 100644 files/uk/web/html/index.html create mode 100644 files/uk/web/html/inline_elements/index.html create mode 100644 "files/uk/web/html/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/html/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/iframe/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/link/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/nav/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/script/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/section/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/style/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/table/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/video/index.html" create mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\276\320\272/index.html" create mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/hidden/index.html" create mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/index.html" create mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/itemscope/index.html" create mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/lang/index.html" create mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/tabindex/index.html" create mode 100644 "files/uk/web/html/\321\200\320\265\320\266\320\270\320\274_\321\201\321\203\320\274\321\226\321\201\320\275\320\276\321\201\321\202\321\226_\320\271_\321\201\321\202\320\260\320\275\320\264\320\260\321\200\321\202\320\275\320\270\320\271_\321\200\320\265\320\266\320\270\320\274/index.html" (limited to 'files/uk/web/html') diff --git a/files/uk/web/html/attributes/index.html b/files/uk/web/html/attributes/index.html new file mode 100644 index 0000000000..f7499d1bf4 --- /dev/null +++ b/files/uk/web/html/attributes/index.html @@ -0,0 +1,654 @@ +--- +title: HTML attribute reference +slug: Web/HTML/Attributes +translation_of: Web/HTML/Attributes +--- +

Елементи в HTML можуть мати атрибути; це додаткові величини, які певним чином змінюють безпосередньо елементи або їх поведінку для отримання необхідного користувачеві ефекту.

+ +

Список атрибутів

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Назва атрибутуЕлементиОпис
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Список типів даних, що приймає сервер, зазвичай, типів файлів.
accept-charset{{ HTMLElement("form") }}Список кодувань, які підтримуються.
accesskeyГлобальний атрибутВизначає комбінацію клавіш швидкого доступу для активації або фокусування на елементі.
action{{ HTMLElement("form") }}URI програми, яка обробляє інформацію, передану формою.
align{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }},  {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }},  {{ HTMLElement("td") }},  {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}Визначає вирівнювання елементу по горизогталі
alt{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}Показує альтарнативний текст у разі неможливості відобразити зображення.
async{{ HTMLElement("script") }}Вказуєна те, що скрипт повинен виконуватися асинхронно.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Вказує чи дозволено автозаповнення полів браузером.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Після завантаження сторінки, відбуватиметься автоматичне фокусування на цьому елементі.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Відтворює аудіо чи відео одразу, коли це стає можливим.
autosave{{ HTMLElement("input") }}Попередні значення повинні зберігатися у випадному списку, щоб можна було обрати значення з різних завантажень сторніки.
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} +

Визначає колір заднього фону елементу.

+ +
+

Примітка: Це застарілий атрибут. Натомість краще використовувати CSS-властивість {{ Cssxref("background-color") }}.

+
+
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} +

Ширина границі.

+ +
+

Примітка: Це застарілий атрибут. Натомість краще використовувати CSS-властивість {{ Cssxref("border") }}.

+
+
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Містить тривалість часу буферованого медіафайлу.
challenge{{ HTMLElement("keygen") }}A challenge string that is submitted along with the public key.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}Оголошує кодування символів сторінки або скрипту.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}Вказує чи слід перевіряти елемент при завантаженні сторінки.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}Містить URI, що вказує на джерело цитати або зміни.
classГлобальний атрибутЧасто використовують з CSS для задання стилю елементів зі спільними властивостями.
code{{ HTMLElement("applet") }}Вказує URL файла класу аплету для завантаження та виконання.
codebase{{ HTMLElement("applet") }}Цей атрибут надає абсолютну чи відносну URL директорії, де зберігаються файли .class аплету.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} +

Цей атрибут задає колір тексту за назвою кольору або його кодом у шістнадцятковому форматі RRGGBB.

+ +
+

Примітка: Це застарілий атрибут. Натомість краще використовувати CSS-власивість {{ Cssxref("color") }}

+
+
cols{{ HTMLElement("textarea") }}Задає кількість колонок в текстовому полі.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Цей атрибут задає кількість стовпців, яку займає одна комірка таблиці вширину.
content{{ HTMLElement("meta") }}Знаення, пов'язане з http-equiv або name залежно від контексту.
contenteditableГлобальний атрибутВказує чи можна змінювати вміст елементу.
contextmenuГлобальний атрибутВизначає ID елементу {{ HTMLElement("menu") }}, який слугуватиме контекстним меню елемента.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Вказує чи браузер відображатиме панель управління медіа користувачеві.
coords{{ HTMLElement("area") }}Набір значень, що задають координати активної області.
crossorigin{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}Визначає як елемент поводиться з запитами до різних джерел.
data{{ HTMLElement("object") }}Задає URL джерела.
data-*Глобальний атрибутДозволяє вам застосовувати до HTML-елемента користувацькі атрибути.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}Вказує час та дату, пов'язані з елементтом.
default{{ HTMLElement("track") }}Indicates that the track should be enabled unless the user's preferences indicate something different.
defer{{ HTMLElement("script") }}Indicates that the script should be executed after the page has been parsed.
dirГлобальний атрибутDefines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Вказує на можливість взаємодії користувача з елементом.
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }}Вказує на те, що посилання використовується для завантаження.
draggableГлобальний атрибутВизначає чи можна перетягувати елемент.
dropzoneГлобальний атрибутВказує чи може елемент приймати перетягування на нього контенту.
enctype{{ HTMLElement("form") }}Defines the content type of the form date when the method is POST.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Описує елементи, які належать до цього елементу.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Визначає форму, яка є батьківською для цього елементу.
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDs of the <th> elements which applies to this element.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

Задає висоту перелічених елементів. Для інших елементів краще використовувати CSS-властивість {{cssxref("height")}}.

+ +
+

Примітка: У деяких випадках, зокрема для {{ HTMLElement("div") }}, це застарілий атрибут. Натомість для нього краще застосовувати CSS-властивість {{ Cssxref("height") }}.

+
+
hiddenГлобальний атрибутНе дозволяє рендеринг певного елемента, але не скасовує рендеринг дочірніх елементів, наприклад, скриптових і активних.
high{{ HTMLElement("meter") }}Вказує нижню межу верхнього діапазону.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }} URL посилання на певне джерело.
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Вказує на мову сторінки, на яку буде перейдено за посиланням.
http-equiv{{ HTMLElement("meta") }} 
icon{{ HTMLElement("command") }}Задає картинку, яка відображає команду.
idГлобальний атрибутЧасто використовується з CSS для задання стилю конкретному елементу. Значення цього атрибути повинно бути унікальним.
integrity{{ HTMLElement("link") }}, {{ HTMLElement("script") }}  +

Додатковий рівень захисту, дає змогу браузеру ідентифікувати, чи він стягує потрібний файл.

+ +

Посилання MDN

+
ismap{{ HTMLElement("img") }}Вказує на те, що зображення є частиною заображення серверної карти.
itempropГлобальний атрибут 
keytype{{ HTMLElement("keygen") }}Визначає тип генерованого ключа.
kind{{ HTMLElement("track") }}Specifies the kind of text track.
label{{ HTMLElement("track") }}Specifies a user-readable title of the text track.
langГлобальний атрибутDefines the language used in the element.
language{{ HTMLElement("script") }}Defines the script language used in the element.
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}Indicates whether the media should start playing from the start when it's finished.
low{{ HTMLElement("meter") }}Indicates the upper bound of the lower range.
manifest{{ HTMLElement("html") }}Specifies the URL of the document's cache manifest.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Indicates the maximum value allowed.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Defines the maximum number of characters allowed in the element.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}Specifies a hint of the media for which the linked resource was designed.
method{{ HTMLElement("form") }}Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}Indicates the minimum value allowed.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Indicates whether multiple values can be entered in an input of the type email or file.
muted{{ HTMLElement("video") }}Indicates whether the audio will be initially silenced on page load.
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }}Name of the element. For example used by the server to identify the fields in form submits.
novalidate{{ HTMLElement("form") }}This attribute indicates that the form shouldn't be validated when submitted.
open{{ HTMLElement("details") }}Indicates whether the details will be shown on page load.
optimum{{ HTMLElement("meter") }}Indicates the optimal numeric value.
pattern{{ HTMLElement("input") }}Defines a regular expression which the element's value will be validated against.
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Дає підказку користувачу про те, які дані треба вводити в поле.
poster{{ HTMLElement("video") }}URL, що відображає рамку постера під час програвання або пошуку.
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Вказує, чи потребує попереднього завантаження контент або його частина.
radiogroup{{ HTMLElement("command") }} 
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Вказує чи можна редагувати цей елемент.
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Визнчає взаємозв'язок даного об'єкту та об'єкту посилання.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Вказує чи заповнення цього елементу є обов'язковим.
reversed{{ HTMLElement("ol") }}Вказує як відображати елементи списку: у порядку зростання чи спадання.
rows{{ HTMLElement("textarea") }}Визначає кількість рядків у текстовому полі.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Визначає кількість рядків, які займає одна комірка таблиці.
sandbox{{ HTMLElement("iframe") }} 
scope{{ HTMLElement("th") }} 
scoped{{ HTMLElement("style") }} 
seamless{{ HTMLElement("iframe") }} 
selected{{ HTMLElement("option") }}Задає значення, яке буде обрано при звантаженні сторінки.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Задає ширину елементу (у пікселях). Якщо елемент є стрічкою або текстом чи паролем, то цей атрибут задає кількість символів в ширину.
sizes{{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }} 
slotГлобальний атрибутВідводить елементу місце у тіньовій моделі документу.
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} 
spellcheckГлобальний атрибутВказує чи дозволена для цього елемента перевірка правопису.
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}URL вбудованого контенту.
srcdoc{{ HTMLElement("iframe") }} 
srclang{{ HTMLElement("track") }} 
srcset{{ HTMLElement("img") }} 
start{{ HTMLElement("ol") }}Задає значення початку відліку, якщо воно повинно бутит відмінним від "1".
step{{ HTMLElement("input") }} 
styleГлобальний атрибутВизначає CSS-стилі, які переписуюють попередньо задані властивості.
summary{{ HTMLElement("table") }} 
tabindexГлобальний атрибутПереписує порядок шарів сторінки за замовчуванням та встановлює свій.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} 
titleГлобальний атрибутТекст, який показується при наведенні курсору на елемент.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}Визначає тип даних елементу.
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}Задає величину, що буде відображатись за замовчуванням після завантаження сторінки.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

Задає ширину для всіх зазначених у списку елементів.

+ +
+

Примітка: У інших випадках, наприклад для елементу  {{ HTMLElement("div") }}, цей атрибут застарілий, і краще використовувати CSS-властивість {{ Cssxref("width") }}.

+
+
wrap{{ HTMLElement("textarea") }}Вказує, чи потрібно додавати нові рядки до тексту.
+ +

Content versus IDL attributes

+ +

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

+ +

The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element.

+ +

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.

+ +

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the type IDL attribute will return the string "text".

+ +

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.

+ +

IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes  behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave.

+ +

Також читай

+ + diff --git a/files/uk/web/html/block-level_elements/index.html b/files/uk/web/html/block-level_elements/index.html new file mode 100644 index 0000000000..2e1b9eef0f --- /dev/null +++ b/files/uk/web/html/block-level_elements/index.html @@ -0,0 +1,133 @@ +--- +title: Блокові елементи +slug: Web/HTML/Block-level_elements +tags: + - HTML + - HTML5 +translation_of: Web/HTML/Block-level_elements +--- +

В HTML (Hypertext Markup Language — мові гіпертекстової розмітки) елементи зазвичай бувають або блокові, або рядкові. Блокові елементи, або блок-елементи, займають всю ширину батьківського блока (контейнера), утворюючи таким чином блок. У цій статті пояснюється, як це працює. 

+ +

Браузери зазвичай відображають кожний блоковий елемент з нового рядка. Це можна уявити як стопку блоків, у якій всі блоки розміщуються над або один під одним. 

+ +
+

Блокові елементи завжди починаються з нового рядка та займають всю доступну ширину (розтягуються ліворуч та праворуч настільки, наскільки це дозволяє ширина вікна браузера).

+
+ +

Приклади нижче показують, як працюють блокові елементи: 

+ +

Блокові елементи

+ +

HTML

+ +
<p>Цей параграф є блоковим елементом; колір його бекграунду змінений, щоб показати батьківський елемент параграфа.</p>
+ +

CSS

+ +
p { background-color: #8ABB55; }
+
+ +

{{ EmbedLiveSample('Block-level_Example') }}

+ +

Застосування

+ + + +

Блокові проти рядкових

+ +

Є кілька ключових відмінностей між блоковими і рядковими елементами:

+ +
+
Форматування
+
Типово, блоковий елемент починається з нового рядка, тоді як рядковий елемент може починатися будь-де в рядку. 
+
Модель контенту
+
Зазвичай блокові елементи можуть містити в собі рядкові елементи, а також інші блокові елементи. Ця структурна відмінність відображає ідею, що блокові елементи утворюють "більші" структури, ніж рядкові елементи.
+
+ +

Розрізнення "блокові елементи vs. рядкові елементи" вживається в специфікаціях HTML до версії 4.01. В HTML5 це протиставлення заміщене більш складними поняттями категорій контенту. Блокові елементи здебільшого відповідають категорії flow content (розміщення контенту) в HTML5, тоді як рядкові — категорії phrasing content (текст і його розмітка), з декількома додатковими категоріями.

+ +

Елементи

+ +

Нижче подається повний перелік усіх блокових елементів HTML (технічно, у нових елементів, представлених у HTML5, "блоковість" вже не визначається). 

+ +
+
+
{{ HTMLElement("address") }}
+
Контактна інформація.
+
{{ HTMLElement("article") }} {{ HTMLVersionInline(5) }}
+
Вміст статті.
+
{{ HTMLElement("aside") }} {{ HTMLVersionInline(5) }}
+
Бічний контент.
+
{{ HTMLElement("blockquote") }}
+
Довга блок-цитата.
+
{{ HTMLElement("canvas") }} {{ HTMLVersionInline(5) }}
+
Канва для малюнків.
+
{{ HTMLElement("dd") }}
+
Описує термін в переліку визначень.
+
{{ HTMLElement("div") }}
+
Поділ документа.
+
{{ HTMLElement("dl") }}
+
Перелік визначень.
+
{{ HTMLElement("dt") }}
+
Термін в переліку визначень.
+
{{ HTMLElement("fieldset") }}
+
Лейбл (назва) для набору полів.
+
+ +
+
{{ HTMLElement("figcaption") }} {{ HTMLVersionInline(5) }}
+
Підпис зображення.
+
{{ HTMLElement("figure") }} {{ HTMLVersionInline(5) }}
+
Групує медіаконтент з підписом (див. {{ HTMLElement("figcaption") }}).
+
{{ HTMLElement("footer") }} {{ HTMLVersionInline(5) }}
+
Секція або футер сторінки. 
+
{{ HTMLElement("form") }}
+
Форма введення.
+
{{ HTMLElement("h1") }}, {{ HTMLElement("h2") }}, {{ HTMLElement("h3") }}, {{ HTMLElement("h4") }}, {{ HTMLElement("h5") }}, {{ HTMLElement("h6") }}
+
Заголовки рівнів 1-6.
+
{{ HTMLElement("header") }} {{ HTMLVersionInline(5) }}
+
Секція або хедер сторінки.
+
{{ HTMLElement("hgroup") }} {{ HTMLVersionInline(5) }}
+
Групує контент хедера.
+
{{ HTMLElement("hr") }}
+
Горизонтальна роздільна лінія.
+
{{ HTMLElement("li") }}
+
Пункт переліку.
+
{{ HTMLElement("main") }}
+
Містить основний контент, унікальний для цього документу.
+
{{ HTMLElement("nav") }}
+
Містить навігацію посилань. 
+
+ +
+
{{ HTMLElement("noscript") }}
+
Контент, який буде відображатися, якщо скрипт не підтримується або вимкнений. 
+
{{ HTMLElement("ol") }}
+
Нумерований список (перелік).
+
{{ HTMLElement("output") }} {{ HTMLVersionInline(5) }}
+
Вихідні дані форми.
+
{{ HTMLElement("p") }}
+
Параграф.
+
{{ HTMLElement("pre") }}
+
Попередньо відформатований текст.
+
{{ HTMLElement("section") }} {{ HTMLVersionInline(5) }}
+
Секція веб-сторінки.
+
{{ HTMLElement("table") }}
+
Таблиця.
+
{{ HTMLElement("tfoot") }}
+
Футер таблиці.
+
{{ HTMLElement("ul") }}
+
Ненумерований список (перелік).
+
{{ HTMLElement("video") }} {{ HTMLVersionInline(5) }}
+
Відеоплеєр.
+
+
+ +


+ Також дивися:

+ + diff --git a/files/uk/web/html/element/input/date/index.html b/files/uk/web/html/element/input/date/index.html new file mode 100644 index 0000000000..1737d7786a --- /dev/null +++ b/files/uk/web/html/element/input/date/index.html @@ -0,0 +1,510 @@ +--- +title: +slug: Web/HTML/Element/input/date +translation_of: Web/HTML/Element/input/date +--- +
{{HTMLRef}}
+ +

{{HTMLElement("input")}} елементи типу date створюють поле вводу дати з вбудованим інтерфейсом вибору. Результатом вибору будуть рік, місяць та день, без часу. time та datetime-local поля підтримують вибір часу та дати і часу.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-date.html", "tabbed-shorter")}}
+ + + +

UI віджет змінюється від оглядача к оглядачу; для перегляду сумісності дивіться {{anch("Browser compatibility")}}. Якщо оглядач не підтримує такий віджет, він буде відображений просто як <input type="text">.

+ +

Серед оглядачів які підтримуюсь кастомний інтерфейс вибору дати є Chrome/Opera, який виглядає наступним чином:

+ +

+ +

Edge вибор дати виглядає так:

+ +

+ +

У Firefox вибір дати буде таким:

+ +

Datepicker UI in firefox

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}{{domxref("DOMString")}} представляє дату у YYYY-MM-DD форматі, або пустим
Події{{event("change")}} та {{event("input")}}
Підримка атрибутів{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, та {{htmlattrxref("step", "input")}}
IDL атрибутиlist, value, valueAsDate, valueAsNumber.
Методи{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}
+ +

Значення

+ +

{{domxref("DOMString")}} представляє значення дати введенної у input. Формат дати описаний у {{SectionOnPage("/en-US/docs/Web/HTML/Date_and_time_formats", "Format of a valid date string")}}.

+ +

Ви можете встановити значення за замовчуванням встановивши дату в атрибут {{htmlattrxref("value", "input")}} , наприклад:

+ +
<input id="date" type="date" value="2017-06-01">
+ +

{{EmbedLiveSample('Value', 600, 40)}}

+ +

Треба пам'ятати що відображений формат відрізняється від актуального value — відображення формату дати буде вибрано на основі вибраної локалі користувальницького оглядача, тоді як value дати завжди є у форматі yyyy-mm-dd.

+ +

Ви також можете взяти чи встановити значення дати у JavaScript використовуючи властивість елементу {{domxref("HTMLInputElement.value", "value")}} , наприклад:

+ +
var dateControl = document.querySelector('input[type="date"]');
+dateControl.value = '2017-06-01';
+ +

Цей код знаходить перший {{HTMLElement("input")}} елемент type якого є date і встановлює його значення 2017-06-01 (June 1, 2017).

+ +

Додаткові атрибути

+ +

Додатково з загальними атрибутами {{HTMLElement("input")}} "date" надає наступні додаткові атрибути:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
АтрибутОпис
{{anch("max")}}Максимальна дата яка може бути введена
{{anch("min")}}Мінімальна дата
{{anch("readonly")}}Чи є у інпута контент чи нема, він лише для считування
{{anch("step")}}Інтервал 
+ +

{{htmlattrdef("max")}}

+ +

Остання дата. Якщо встановлена дата {{htmlattrxref("value", "input")}} більше ніж ця дата, елемент не пройде constraint validation. Якщо значення max не валідна строка формату yyyy-MM-dd, тоді елемент не буде мати максимальне обмеження.

+ +

Це значення має вказувати дату пізнішу або поточну вказанному атрибуту min.

+ +

{{htmlattrdef("min")}}

+ +

Мінімальна дата; дати раніші за вказану не пройдуть constraint validation. Якщо значення  min атрибуту має неавлідний формат yyyy-MM-dd, тоді елемент не матиме мінімального обмеження.

+ +

Це значення вказує меньшу або еквівалентну значенню атрибута max.

+ +

{{page("/en-US/docs/Web/HTML/Element/input/text", "readonly", 0, 1, 2)}}

+ +

{{htmlattrdef("step")}}

+ +

{{page("/en-US/docs/Web/HTML/Element/input/number", "step-include")}}

+ +

Для date інпутів, значення step вказується в днях, скалярні до 86,400,000 (мілісекунди). За замовчуванная step має 1, означаюче 1 день.

+ +
+

Вказання any для step атрибуту робить той самий ефект як і 1.

+
+ +

Використання date інпутів

+ +

Поле введення дати зручні на перший погляд — вони надають легкий UI(користувальницький інтерфейс) для вибору дати, і нормалізують формат даних для відправки на сервер, незважаючи на локаль користувача. Однак, існують проблеми підтримки деякими оглядачами <input type="date">.

+ +

Подивимось на базові та комлексні використання <input type="date">, щодо сумісності оглядачів ви можете порадитись за посиланням (see {{anch("Handling browser support")}}). Звичайно, з часом підтримка в оглядачах розповсюдиться. і усі проблеми будуть вирішені.

+ +

Базові використання date

+ +

Найпростіше використання <input type="date"> передбачає базову <input> і {{htmlelement("label")}} комбінацію елементів, як бачимо нижче:

+ +
<form>
+  <div>
+    <label for="bday">Enter your birthday:</label>
+    <input type="date" id="bday" name="bday">
+  </div>
+</form>
+ +

{{EmbedLiveSample('Basic_uses_of_date', 600, 40)}}

+ +

Встановлення мінімальной і максимальної дати

+ +

Ви можете використовувати {{htmlattrxref("min", "input")}} і {{htmlattrxref("max", "input")}} атрибути щоб обмежити дати які будуть вибрані користувачем. В наступному прикладі ми встановлюємо мінімальну дату 2017-04-01 і максимальну дату 2017-04-30:

+ +
<form>
+  <div>
+    <label for="party">Choose your preferred party date:</label>
+    <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-30">
+  </div>
+</form>
+ +

{{EmbedLiveSample('Setting_maximum_and_minimum_dates', 600, 40)}}

+ +

Результатом будуть лише дні в Квітні 2017го які можно буде вибрати — тільки "дні", частина текстового значення будуть можливі для зміни, дати поза Квітнем не будуть проскролюватись у віджеті.

+ +
+

Примітка: Ви можете використати {{htmlattrxref("step", "input")}} атрибут для того щоб вказати інтервал зміни днів (наприклад ви хотіли б щоб можно були вибрати лише Неділю). Однак, це не завжди ефективно в тих чи іншіх реалізаціях.

+
+ +

Контроль розміру input

+ +

<input type="date"> не підтримує розмір форми атрибутами наприклад {{htmlattrxref("size", "input")}}. Зверніться до CSS для контролю розміру елементу.

+ +

Валідація

+ +

За замовчуванням, <input type="date"> не додає жодної валідації на введення значення. UI реалізація загалом не дозволяє уведення будь чого що не є датою — що є добре — але ви всеодно можете лишати поле пустим чи (в оглядачах де інпут відображається простим типом text) ввести неправильну дату (наприклад 32ге Квітня).

+ +

Якщо ви використовуєте {{htmlattrxref("min", "input")}} і {{htmlattrxref("max", "input")}} для обмеження введення дат (дивіться {{anch("Setting maximum and minimum dates")}}), підтримуючі оглядачі відобразять помилку якщо ви спробуєте відправити дату поза меж вказаних в атрибутах. Однак, перевірте результат щоб запевнитись що значення всередені цих дат, тому що вони можуть не підтримуватись пристрієм користувача.

+ +

В додаток, ви можете використовувати {{htmlattrxref("required", "input")}} атрибут щоб зробити заповнення дати обьв'язковим — знову ж, буде відображена помилка якщо користувач захоче відправити пусте поле. Принаймні, це буде працювати у більшості оглядачів.

+ +

Давайте розглянемо приклад — ми встановили мінімальну і максимальну дату, і також зробили його обов'язковим:

+ +
<form>
+  <div>
+    <label for="party">Choose your preferred party date (required, April 1st to 20th):</label>
+    <input type="date" id="party" name="party" min="2017-04-01" max="2017-04-20" required>
+    <span class="validity"></span>
+  </div>
+  <div>
+    <input type="submit">
+  </div>
+</form>
+ +

Якщо ви спробуєте відправити форму з незаповненою датою(або з датою поза межами), оглядач відобразить помилку. Спробуйте це самі зробити для перевірки:

+ +

{{EmbedLiveSample('Validation', 600, 100)}}

+ +

Це скріншот приклади оглядача без підтримки віджету дати:

+ +

+ +

CSS використаний нижче в прикладі. Ми використовуєм правила {{cssxref(":valid")}} та {{cssxref(":invalid")}} CSS щоб стилізувати відображення валідного чи невалідного введенного значення поля. Ми встановлюємо іконку на {{htmlelement("span")}} біля інпуту, не на самий інпут, тому що у Chrome створений контент розміщений всередені контролю форми, і не може бути застилізований чи відображений коректно.

+ +
div {
+    margin-bottom: 10px;
+    display: flex;
+    align-items: center;
+}
+
+label {
+  display: inline-block;
+  width: 300px;
+}
+
+input:invalid+span:after {
+    content: '✖';
+    padding-left: 5px;
+}
+
+input:valid+span:after {
+    content: '✓';
+    padding-left: 5px;
+}
+ +
+

Важливо: HTML валідація форми не замінює скрипти які перевіряють чи буле введена інформація у коректному форматі. Це достатньо простий метод щоб додати корекцію до HTML, їх можливо обійти , чи видалити зовсім. Якщо ваша серверна сторона не перевірить відправлені данні, це може бути катастрофа (данні можуть бути дуже великого розміру, або неправильного типу, вам можуть завантажити скрипт взлому і так далі).

+
+ +

Обробка підтримки оглядачів

+ +

Як згадано раніше, більша частина проблем з використанням інпуту дати описани  у {{anch("Browser compatibility", "browser support")}}. Як приклад, дата пікер у Firefox для Android виглядає так:

+ +

+ +

Непідтримуючи оглядачі точно деградують інпут, це створює проблеми у якості інтерфейсу користувача (представлеий віджет буде іншим), і обробкою даних.

+ +

Наступна проблема це більш серьозна; як згадували раніше, за інпутом дати, данні завжди нормалізуються у формат yyyy-mm-dd. З текстовим інпутом оглядач не підтримує формат введених даних, і є багато прикладів як люди вводять дати, наприклад:

+ + + +

Єдиний спосіб стосовно цього є лише введення атрибуту {{htmlattrxref("pattern", "input")}}. Якщо інпут дати не використовує цей атрибут, то текстовий буде. Наприклад, розгляньте код у непідтримуючих оглядачах:

+ +
<form>
+  <div>
+    <label for="bday">Enter your birthday:</label>
+    <input type="date" id="bday" name="bday" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">
+    <span class="validity"></span>
+  </div>
+  <div>
+    <input type="submit">
+  </div>
+</form>
+ +

{{EmbedLiveSample('Handling_browser_support', 600, 100)}}

+ +

Якщо ви спробуєте відправити це, ви побачете помилку (інпут підсвітеться як невалідний) якщо ви ввели данні які не збігаються з шаблоном nnnn-nn-nn, де n номер від 0 до 9. Звичайно, це не зупинить людей від введення неправильної дати, чи введення у неправильному форматі, як yyyy-dd-mm (де ми очикуємо yyyy-mm-dd). Тож всеж таки маємо проблему.

+ + + +

Найкращий шлях опрацьовувати дати в формах в крос-браузерному форматі на даний момент є введення користувачем дня, місяця, і року в окремих елементах ({{htmlelement("select")}}; (дивіться далі реалізацію), або використовуючи JavaScript бібліотеку jQuery date picker.

+ +

Приклади

+ +

В цьому прикладі ми створюємо два набори UI елементів для вибору дат: рідний <input type="date"> і набір із трьох {{htmlelement("select")}} елементів для вибору дати в тих оглядачах які не підтримують рідний date інпут.

+ +

{{EmbedLiveSample('Examples', 600, 100)}}

+ +

HTML

+ +

HTML виглядає так:

+ +
<form>
+    <div class="nativeDatePicker">
+      <label for="bday">Enter your birthday:</label>
+      <input type="date" id="bday" name="bday">
+      <span class="validity"></span>
+    </div>
+    <p class="fallbackLabel">Enter your birthday:</p>
+    <div class="fallbackDatePicker">
+      <span>
+        <label for="day">Day:</label>
+        <select id="day" name="day">
+        </select>
+      </span>
+      <span>
+        <label for="month">Month:</label>
+        <select id="month" name="month">
+          <option selected>January</option>
+          <option>February</option>
+          <option>March</option>
+          <option>April</option>
+          <option>May</option>
+          <option>June</option>
+          <option>July</option>
+          <option>August</option>
+          <option>September</option>
+          <option>October</option>
+          <option>November</option>
+          <option>December</option>
+        </select>
+      </span>
+      <span>
+        <label for="year">Year:</label>
+        <select id="year" name="year">
+        </select>
+      </span>
+    </div>
+</form>
+ +

Назви місяців жорстко закодовані (тому що вони завжди однакові), коли дні і роки динамічно згенеровані залежно від того який місяць і рік вибраний, і поточний рік (дивіться коментарі коду нижче для детального пояснення як ці функції працюють).

+ + + +

JavaScript

+ +

Друга частина коду розраховує чи підтримує оглядач <input type="date">, ми створюєм {{htmlelement("input")}} елемент, із type date, потім одразу перевіряємо який тип було встановлено — непідтримуючі оглядачі автоматично повернуть тип text, тому що date тип автоматично перетворюється на text. Якщо <input type="date"> не підтримується, ми приховуємо рідний інпут і показуєм UI ({{htmlelement("select")}}) замість нього.

+ +
// define variables
+var nativePicker = document.querySelector('.nativeDatePicker');
+var fallbackPicker = document.querySelector('.fallbackDatePicker');
+var fallbackLabel = document.querySelector('.fallbackLabel');
+
+var yearSelect = document.querySelector('#year');
+var monthSelect = document.querySelector('#month');
+var daySelect = document.querySelector('#day');
+
+// hide fallback initially
+fallbackPicker.style.display = 'none';
+fallbackLabel.style.display = 'none';
+
+// test whether a new date input falls back to a text input or not
+var test = document.createElement('input');
+test.type = 'date';
+
+// if it does, run the code inside the if() {} block
+if(test.type === 'text') {
+  // hide the native picker and show the fallback
+  nativePicker.style.display = 'none';
+  fallbackPicker.style.display = 'block';
+  fallbackLabel.style.display = 'block';
+
+  // populate the days and years dynamically
+  // (the months are always the same, therefore hardcoded)
+  populateDays(monthSelect.value);
+  populateYears();
+}
+
+function populateDays(month) {
+  // delete the current set of <option> elements out of the
+  // day <select>, ready for the next set to be injected
+  while(daySelect.firstChild){
+    daySelect.removeChild(daySelect.firstChild);
+  }
+
+  // Create variable to hold new number of days to inject
+  var dayNum;
+
+  // 31 or 30 days?
+  if(month === 'January' || month === 'March' || month === 'May' || month === 'July' || month === 'August' || month === 'October' || month === 'December') {
+    dayNum = 31;
+  } else if(month === 'April' || month === 'June' || month === 'September' || month === 'November') {
+    dayNum = 30;
+  } else {
+  // If month is February, calculate whether it is a leap year or not
+    var year = yearSelect.value;
+    var isLeap = new Date(year, 1, 29).getMonth() == 1;
+    isLeap ? dayNum = 29 : dayNum = 28;
+  }
+
+  // inject the right number of new <option> elements into the day <select>
+  for(i = 1; i <= dayNum; i++) {
+    var option = document.createElement('option');
+    option.textContent = i;
+    daySelect.appendChild(option);
+  }
+
+  // if previous day has already been set, set daySelect's value
+  // to that day, to avoid the day jumping back to 1 when you
+  // change the year
+  if(previousDay) {
+    daySelect.value = previousDay;
+
+    // If the previous day was set to a high number, say 31, and then
+    // you chose a month with less total days in it (e.g. February),
+    // this part of the code ensures that the highest day available
+    // is selected, rather than showing a blank daySelect
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 1;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 2;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 3;
+    }
+  }
+}
+
+function populateYears() {
+  // get this year as a number
+  var date = new Date();
+  var year = date.getFullYear();
+
+  // Make this year, and the 100 years before it available in the year <select>
+  for(var i = 0; i <= 100; i++) {
+    var option = document.createElement('option');
+    option.textContent = year-i;
+    yearSelect.appendChild(option);
+  }
+}
+
+// when the month or year <select> values are changed, rerun populateDays()
+// in case the change affected the number of available days
+yearSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+monthSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+//preserve day selection
+var previousDay;
+
+// update what day has been set to previously
+// see end of populateDays() for usage
+daySelect.onchange = function() {
+  previousDay = daySelect.value;
+}
+ +
+

Note: Remember that some years have 53 weeks in them (see Weeks per year)! You'll need to take this into consideration when developing production apps.

+
+ +

Специфікації

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{SpecName('HTML WHATWG', 'forms.html#date-state-(type=date)', '<input type="date">')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'forms.html#date-state-(type=date)', '<input type="date">')}}{{Spec2('HTML5 W3C')}}
+ +

Сумісність з оглядачами

+ + + +

{{Compat("html.elements.input.input-date")}}

+ +

Дивіться також

+ + diff --git a/files/uk/web/html/element/input/datetime-local/index.html b/files/uk/web/html/element/input/datetime-local/index.html new file mode 100644 index 0000000000..b8e88ea62e --- /dev/null +++ b/files/uk/web/html/element/input/datetime-local/index.html @@ -0,0 +1,543 @@ +--- +title: +slug: Web/HTML/Element/input/datetime-local +translation_of: Web/HTML/Element/input/datetime-local +--- +
{{HTMLRef}}
+ +

{{htmlelement("input")}} типу datetime-local створює елемент керування, який дозволяє користувачу легко вводити і дату, і час, включаючи рік, місяць, день і час у годинах і хвилинах. Застосовується часовий пояс користувача. Вигляд елемента змінюється в загальному залежно від браузера; на даний час його підтримка є непостійною, для настільних пристроїв тільки Chrome/Opera й Edge, а для мобільних тільки найновіші браузери мають дієві його розробки. В інших браузерах вони занепали до простих елементів типу <input type="text">.

+ +

Про підтримку секунд нема й мови.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-datetime-local.html", "tabbed-standard")}}
+ + + +
+

Примітка: Через обмежену підтримку браузерами формату datetime-local, і відмінності в роботі елементів введення "input", на даний час, можливо, краще було би вживати якийсь фреймворк чи бібліотеку для їх відображення або використовувати ваш власний елемент введення. Іншим підходом може бути вживання окремих елементів date і time, кожен з яких підтримується ширше, ніж datetime-local.

+
+ +

Також деякі браузери для введення часу можуть вдаватися тільки до елемента текстового типу, що перевіряє, чи введені символи становлять правильні значення дати/часу перед відправленням їх на сервер, але небажано покладатися на цей підхід, оскільки його поведінку важко передбачити.

+ +

Для тих із вас, хто не користується браузером із підтримкою datetime-local, елементи керування у Chrome/Opera виглядатимуть як на наступному знімку. Клацнувши справа значок стрілочки вниз, ви отримаєте вибирач дати, а час маєте ввести вручну.

+ +

+ +

The Edge datetime-local control looks like the below; clicking the date and the time parts of the value bring up two separate pickers for you, so you can easily set both the date and the time. This is somewhat like having date and time widgets both created for you and merged into one.

+ +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + +
{{anch("Value")}}A {{domxref("DOMString")}} representing a date and time (in the local time zone), or empty.
Events{{event("change")}} and {{event("input")}}.
Supported Common Attributes{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, and {{htmlattrxref("step", "input")}}.
IDL attributeslist, value, valueAsNumber.
Methods{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}.
+ +

Value

+ +

A {{domxref("DOMString")}} representing the value of the date entered into the input. You can set a default value for the input by including a date and time inside the {{htmlattrxref("value", "input")}} attribute, like so:

+ +
<label for="party">Enter a date and time for your party booking:</label>
+<input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30">
+ +

{{ EmbedLiveSample('Value', 600, 60) }}

+ +

One thing to note is that the displayed date and time formats differ from the actual value; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time value is always formatted yyyy-MM-ddThh:mm. When the above value submitted to the server, for example, it will look like "partydate=2017-06-01T08:30".

+ +
+

Note: Also bear in mind that if such data is submitted via HTTP GET, the colon character will need to be escaped for inclusion in the URL parameters, e.g. partydate=2017-06-01T08%3A30. See {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} for one way to do this.

+
+ +

You can also get and set the date value in JavaScript using the {{domxref("HTMLInputElement.value")}} property, for example:

+ +
var dateControl = document.querySelector('input[type="datetime-local"]');
+dateControl.value = '2017-06-01T08:30';
+ +

There are several methods provided by JavaScript's {{jsxref("Date")}} that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. For example, the {{jsxref("Date.toISOString()")}} method can be used for this purpose.

+ +

Using datetime-local inputs

+ +

Date/time inputs sound convenient at first glance; they provide an easy UI for choosing dates and times, and they normalize the data format sent to the server, regardless of the user's locale. However, there are issues with <input type="datetime-local"> because of the limited browser support.

+ +

We'll look at basic and more complex uses of <input type="datetime-local">, then offer advice on mitigating the browser support issue later on (see {{anch("Handling browser support")}}).

+ +

Basic uses of datetime-local

+ +

The simplest use of <input type="datetime-local"> involves a basic <input> and {{htmlelement("label")}} element combination, as seen below:

+ +
<form>
+    <label for="party">Enter a date and time for your party booking:</label>
+    <input id="party" type="datetime-local" name="partydate">
+</form>
+ +

{{ EmbedLiveSample('Basic_uses_of_datetime-local', 600, 40) }}

+ +

Setting maximum and minimum dates and times

+ +

You can use the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes to restrict the dates/times that can be chosen by the user. In the following example we are setting a minimum datetime of 2017-06-01T08:30 and a maximum datetime of 2017-06-30T16:30:

+ +
  <form>
+    <label for="party">Enter a date and time for your party booking:</label>
+    <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30">
+  </form>
+ +

{{ EmbedLiveSample('Setting_maximum_and_minimum_dates_and_times', 600, 40) }}

+ +

The result here is that:

+ + + +
+

Note: You should be able to use the {{htmlattrxref("step", "input")}} attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.

+
+ +

Controlling input size

+ +

<input type="datetime-local"> doesn't support form control sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to CSS for customizing the sizes of these elements.

+ +

Setting timezones

+ +

One thing the datetime-local input type doesn't provide is a way to set the time zone and/or locale of the date/time control. This was available in the datetime input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers, and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control.

+ +

For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a hidden input type. For example:

+ +
<input type="hidden" id="timezone" name="timezone" value="-08:00">
+ +

On the other hand, if you were required to allow the user to enter a timezone along with a date/time input, you could provide a means of inputting a timezone, such as a {{htmlelement("select")}} element:

+ +
<select name="timezone_offset" id="timezone-offset" class="span5">
+    <option value="-12:00">(GMT -12:00) Eniwetok, Kwajalein</option>
+    <option value="-11:00">(GMT -11:00) Midway Island, Samoa</option>
+    <option value="-10:00">(GMT -10:00) Hawaii</option>
+    <option value="-09:50">(GMT -9:30) Taiohae</option>
+    <option value="-09:00">(GMT -9:00) Alaska</option>
+    <option value="-08:00">(GMT -8:00) Pacific Time (US &amp; Canada)</option>
+
+  ...
+
+</select>
+ +

In either case, the date/time and time zone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side.

+ +
+

Note: The above code snippet is taken from All world timezones in an HTML select element.

+
+ +

Validation

+ +

By default, <input type="datetime-local"> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of April).

+ +

You can use {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} to restrict the available dates (see anch("Setting maximum and minimum dates")), and you can use the {{htmlattrxref("required", "input")}} attribute to make filling in the date/time mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field.

+ +

Let's look at an example; here we've set minimum and maximum date/time values, and also made the field required:

+ +
<form>
+    <div>
+        <label for="party">Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm):</label>
+        <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" required>
+        <span class="validity"></span>
+    </div>
+    <div>
+        <input type="submit" value="Book party!">
+    </div>
+</form>
+ +

If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:

+ +

{{ EmbedLiveSample('Validation', 600, 120) }}

+ +

Here's a screenshot for those of you who aren't using a supporting browser:

+ +

+ +

Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a {{htmlelement("span")}} next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively.

+ +
div {
+    margin-bottom: 10px;
+    display: flex;
+    align-items: center;
+}
+
+label {
+  display: inline-block;
+  width: 300px;
+}
+
+input:invalid+span:after {
+    content: '✖';
+    padding-left: 5px;
+}
+
+input:valid+span:after {
+    content: '✓';
+    padding-left: 5px;
+}
+ +
+

Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format.  It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).

+
+ +

Handling browser support

+ +

As mentioned above, the major problem with using date inputs at the time of writing is browser support — only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the datetime-local picker on Firefox for Android looks like this:

+ +

+ +

Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.

+ +

The second problem is the most serious; as we mentioned earlier, with a datetime-local input, the actual value is always normalized to the format yyyy-mm-ddThh:mm. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates and times, for example:

+ + + +

One way around this is to put a {{htmlattrxref("pattern", "input")}} attribute on your datetime-local input. Even though the datetime-local input doesn't use it, the text input fallback will. For example, try viewing the following demo in a non-supporting browser:

+ +
<form>
+  <div>
+    <label for="party">Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm):</label>
+    <input id="party" type="datetime-local" name="partydate"
+           min="2017-06-01T08:30" max="2017-06-30T16:30"
+           pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required>
+    <span class="validity"></span>
+  </div>
+  <div>
+    <input type="submit" value="Book party!">
+  </div>
+  <input type="hidden" id="timezone" name="timezone" value="-08:00">
+</form>
+ +

{{ EmbedLiveSample('Handling_browser_support', 600, 100) }}

+ +

If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern nnnn-nn-nnTnn:nn, where n is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates and times.

+ +

And what user is going to understand the pattern they need to enter the time and date in?

+ +

We still have a problem.

+ + + +

The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, year, and time in separate controls ({{htmlelement("select")}} elements being popular — see below for an implementation), or use JavaScript libraries such as jQuery date picker, and the jQuery timepicker plugin.

+ +

Examples

+ +

In this example we create two sets of UI elements for choosing datetimes — a native <input type="datetime-local"> picker, and a set of five {{htmlelement("select")}} elements for choosing dates and times in older browsers that don't support the native input.

+ +

{{ EmbedLiveSample('Examples', 600, 140) }}

+ +

The HTML looks like so:

+ +
<form>
+  <div class="nativeDateTimePicker">
+    <label for="party">Choose a date and time for your party:</label>
+    <input type="datetime-local" id="party" name="bday">
+    <span class="validity"></span>
+  </div>
+  <p class="fallbackLabel">Choose a date and time for your party:</p>
+  <div class="fallbackDateTimePicker">
+    <div>
+      <span>
+        <label for="day">Day:</label>
+        <select id="day" name="day">
+        </select>
+      </span>
+      <span>
+        <label for="month">Month:</label>
+        <select id="month" name="month">
+          <option selected>January</option>
+          <option>February</option>
+          <option>March</option>
+          <option>April</option>
+          <option>May</option>
+          <option>June</option>
+          <option>July</option>
+          <option>August</option>
+          <option>September</option>
+          <option>October</option>
+          <option>November</option>
+          <option>December</option>
+        </select>
+      </span>
+      <span>
+        <label for="year">Year:</label>
+        <select id="year" name="year">
+        </select>
+      </span>
+    </div>
+    <div>
+      <span>
+        <label for="hour">Hour:</label>
+        <select id="hour" name="hour">
+        </select>
+      </span>
+      <span>
+        <label for="minute">Minute:</label>
+        <select id="minute" name="minute">
+        </select>
+      </span>
+    </div>
+  </div>
+</form>
+ +

The months are hard-coded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year respectively (see the code comments below for detailed explanations of how these functions work.) We also decided to dynamically generate the hours and minutes, as there are so many of them!

+ + + +

The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="datetime-local">, we create a new {{htmlelement("input")}} element, set its type to datetime-local, then immediately check what its type is set to. Browsers that don't support datetime-local return text, since that's what datetime-local falls back to. If <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker UI ({{htmlelement("select")}}) instead.

+ +
// define variables
+var nativePicker = document.querySelector('.nativeDateTimePicker');
+var fallbackPicker = document.querySelector('.fallbackDateTimePicker');
+var fallbackLabel = document.querySelector('.fallbackLabel');
+
+var yearSelect = document.querySelector('#year');
+var monthSelect = document.querySelector('#month');
+var daySelect = document.querySelector('#day');
+var hourSelect = document.querySelector('#hour');
+var minuteSelect = document.querySelector('#minute');
+
+// hide fallback initially
+fallbackPicker.style.display = 'none';
+fallbackLabel.style.display = 'none';
+
+// test whether a new datetime-local input falls back to a text input or not
+var test = document.createElement('input');
+test.type = 'datetime-local';
+// if it does, run the code inside the if() {} block
+if(test.type === 'text') {
+  // hide the native picker and show the fallback
+  nativePicker.style.display = 'none';
+  fallbackPicker.style.display = 'block';
+  fallbackLabel.style.display = 'block';
+
+  // populate the days and years dynamically
+  // (the months are always the same, therefore hardcoded)
+  populateDays(monthSelect.value);
+  populateYears();
+  populateHours();
+  populateMinutes();
+}
+
+function populateDays(month) {
+  // delete the current set of <option> elements out of the
+  // day <select>, ready for the next set to be injected
+  while(daySelect.firstChild){
+    daySelect.removeChild(daySelect.firstChild);
+  }
+
+  // Create variable to hold new number of days to inject
+  var dayNum;
+
+  // 31 or 30 days?
+  if(month === 'January' | month === 'March' | month === 'May' | month === 'July' | month === 'August' | month === 'October' | month === 'December') {
+    dayNum = 31;
+  } else if(month === 'April' | month === 'June' | month === 'September' | month === 'November') {
+    dayNum = 30;
+  } else {
+  // If month is February, calculate whether it is a leap year or not
+    var year = yearSelect.value;
+    (year - 2016) % 4 === 0 ? dayNum = 29 : dayNum = 28;
+  }
+
+  // inject the right number of new <option> elements into the day <select>
+  for(i = 1; i <= dayNum; i++) {
+    var option = document.createElement('option');
+    option.textContent = i;
+    daySelect.appendChild(option);
+  }
+
+  // if previous day has already been set, set daySelect's value
+  // to that day, to avoid the day jumping back to 1 when you
+  // change the year
+  if(previousDay) {
+    daySelect.value = previousDay;
+
+    // If the previous day was set to a high number, say 31, and then
+    // you chose a month with less total days in it (e.g. February),
+    // this part of the code ensures that the highest day available
+    // is selected, rather than showing a blank daySelect
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 1;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 2;
+    }
+
+    if(daySelect.value === "") {
+      daySelect.value = previousDay - 3;
+    }
+  }
+}
+
+function populateYears() {
+  // get this year as a number
+  var date = new Date();
+  var year = date.getFullYear();
+
+  // Make this year, and the 100 years before it available in the year <select>
+  for(var i = 0; i <= 100; i++) {
+    var option = document.createElement('option');
+    option.textContent = year-i;
+    yearSelect.appendChild(option);
+  }
+}
+
+function populateHours() {
+  // populate the hours <select> with the 24 hours of the day
+  for(var i = 0; i <= 23; i++) {
+    var option = document.createElement('option');
+    option.textContent = (i < 10) ? ("0" + i) : i;
+    hourSelect.appendChild(option);
+  }
+}
+
+function populateMinutes() {
+  // populate the minutes <select> with the 60 hours of each minute
+  for(var i = 0; i <= 59; i++) {
+    var option = document.createElement('option');
+    option.textContent = (i < 10) ? ("0" + i) : i;
+    minuteSelect.appendChild(option);
+  }
+}
+
+// when the month or year <select> values are changed, rerun populateDays()
+// in case the change affected the number of available days
+yearSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+monthSelect.onchange = function() {
+  populateDays(monthSelect.value);
+}
+
+//preserve day selection
+var previousDay;
+
+// update what day has been set to previously
+// see end of populateDays() for usage
+daySelect.onchange = function() {
+  previousDay = daySelect.value;
+}
+ +
+

Note: Remember that some years have 53 weeks in them (see Weeks per year)! You'll need to take this into consideration when developing production apps.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{SpecName('HTML WHATWG', 'forms.html#local-date-and-time-state-(type=datetime-local)', '<input type="datetime-local">')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'forms.html##local-date-and-time-state-(type=datetime-local)', '<input type="datetime-local">')}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input.input-datetime-local")}}

+ +

See also

+ + diff --git a/files/uk/web/html/element/input/index.html b/files/uk/web/html/element/input/index.html new file mode 100644 index 0000000000..3c0f2289b3 --- /dev/null +++ b/files/uk/web/html/element/input/index.html @@ -0,0 +1,753 @@ +--- +title: ': The Input (Form Input) element' +slug: Web/HTML/Element/input +tags: + - Data entry + - Element + - Forms + - HTML + - HTML forms + - HTML input tag + - Input + - MakeBrowserAgnostic + - NeedsBrowserCompatibility + - NeedsMobileBrowserCompatibility + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/HTML/Element/input +--- +
{{HTMLRef}}
+ +

The HTML <input> element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and {{Glossary("user agent")}}.

+ +
{{EmbedInteractiveExample("pages/tabbed/input-input.html", "tabbed-standard")}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Content categoriesFlow content, listed, submittable, resettable, form-associated element, phrasing content. If the {{htmlattrxref("type", "input")}} is not hidden, then labelable element, palpable content.
Permitted contentNone, it is an {{Glossary("empty element")}}.
Tag omissionMust have a start tag and must not have an end tag.
Permitted parentsAny element that accepts phrasing content.
Permitted ARIA roles +
    +
  • type=button: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}, {{ARIARole("tab")}}
  • +
  • type=checkbox: {{ARIARole("button")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("option")}}, {{ARIARole("switch")}}
  • +
  • type=image: {{ARIARole("link")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}
  • +
  • type=radio: {{ARIARole("menuitemradio")}}
  • +
  • type=color|date|datetime|datetime-local|email|file: None
  • +
  • type=hidden|month|number|password|range|reset: None
  • +
  • type=search|submit|tel|text|url|week: None
  • +
+
DOM interface{{domxref("HTMLInputElement")}}
+ +

Form <input> types

+ +

How an <input> works varies considerably depending on the value of its type attribute, hence the different types are covered in their own separate reference pages. If this attributes is not specified, the default type adopted is text.

+ +

The available types are as follows:

+ + + +

Some input types are now obsolete:

+ + + +

Attributes

+ +

Global <input> attributes

+ +

This section lists the attributes available to all form <input> types. Non-global attributes — and global attributes that behave differently when specified on different <input> types — are listed on those types' individual pages.

+ +
+

Note: This includes the global HTML attributes.

+
+ +
+
{{htmlattrdef("type")}}
+
The type of control to render. See {{anch("Form <input> types")}} for the individual types, with links to more information about each.
+
{{htmlattrdef("accept")}}
+
If the value of the type attribute is file, this attribute indicates the types of files that the server accepts — otherwise it's ignored. The value must be comma-separated unique “content type specifiers”: +
    +
  • A case-insensitive file extension starting with the STOP character (U+002E). (e.g. .jpg, .png, .doc).
  • +
  • A valid MIME type with no extensions.
  • +
  • audio/* representing sound files. {{HTMLVersionInline("5")}}
  • +
  • video/* representing video files. {{HTMLVersionInline("5")}}
  • +
  • image/* representing image files. {{HTMLVersionInline("5")}}
  • +
+
+
{{htmlattrdef("accesskey")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline", "HTML5")}}
+
Sets a keyboard key that the user can press to focus the control. This attribute is global in HTML5 — see the accesskey page for more info.
+
{{htmlattrdef("autocomplete")}} {{HTMLVersionInline("5")}}
+
This attribute indicates if the input can be automatically completed by the browser, usually by remembering previous values the user has entered. {{page("/en-US/docs/Web/HTML/Attributes/autocomplete", "Values")}}
+
See The HTML autocomplete attribute for additional information.
+
{{htmlattrdef("autofocus")}} {{HTMLVersionInline("5")}}
+
This Boolean attribute specifies that the input should have focus when the page loads, unless the user overrides it (e.g. by typing in a different control). Only one element in a document can have the autofocus attribute. It cannot be applied if the type attribute is hidden, because hidden inputs cannot be focused. Note that the input may be focused before the DOMContentLoaded event fires. +
Warning: Automatically focusing a form control can confuse visually-impaired people who using screen-reading technology. When autofocus is assigned, screen-readers "teleport" their user to the form control without warning them beforehand.
+
+
{{htmlattrdef("capture")}}
+
+

If the value of the type attribute is file, this Boolean attribute indicates that capture of media directly from the device's sensors using a media capture mechanism is preferred, such as a webcam or microphone.

+
+
{{htmlattrdef("checked")}}
+
+

If the value of the type attribute is radio or checkbox, this Boolean attribute pre-checks the control before the user interacts with it.

+ +

Unlike other browsers, Firefox by default persists the dynamic checked state of an <input> across page loads. Use the {{htmlattrxref("autocomplete","input")}} attribute to control this feature.

+
+
{{htmlattrdef("disabled")}}
+
+

This Boolean attribute prevents the user from interacting with the input. In particular, the click event is not dispatched on disabled controls, and disabled controls aren't submitted with their form.

+ +

Unlike other browsers, Firefox will by default persist the dynamic disabled state of an <input> across page loads. Use the {{htmlattrxref("autocomplete","input")}} attribute to control this feature.

+
+
{{htmlattrdef("form")}} {{HTMLVersionInline("5")}}
+
The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a {{HTMLElement("form")}} element in the same document. If this attribute isn't used, the <input> element is associated with its nearest ancestor {{HTMLElement("form")}} element, if any. This attribute lets you to place <input> elements anywhere within a document, not just as descendants of form elements. An input can be associated with at most one form.
+
{{htmlattrdef("formaction")}} {{HTMLVersionInline("5")}}
+
The URL that processes the data submitted by the input element, if it is a submit button or image. This attribute overrides the {{htmlattrxref("action","form")}} attribute of the element's form owner.
+
{{htmlattrdef("formenctype")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this attribute specifies the content encoding that is used to submit the form data to the server. Possible values: +
    +
  • application/x-www-form-urlencoded: The default value if the attribute is not specified.
  • +
  • multipart/form-data: Use this value if you are using an <input> element with the {{htmlattrxref("type","input")}} attribute set to file.
  • +
  • text/plain: This encoding is mostly for debugging.
  • +
+ +

This attribute overrides the {{htmlattrxref("enctype","form")}} attribute of the element's form owner.

+
+
{{htmlattrdef("formmethod")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this attribute specifies the HTTP method that the browser uses to submit the form. Possible values: +
    +
  • post: The data from the form is included in the body of the form and is sent to the server.
  • +
  • get: The data from the form are appended to the form attribute URL, with a '?' as a separator, and the resulting URL is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters.
  • +
+ +

This attribute overrides the {{htmlattrxref("method","form")}} attribute of the element's form owner.

+
+
{{htmlattrdef("formnovalidate")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this Boolean attribute specifies that the form shouldn't be validated before submission. This attribute overrides the {{htmlattrxref("novalidate","form")}} attribute of the element's form owner.
+
{{htmlattrdef("formtarget")}} {{HTMLVersionInline("5")}}
+
If the input element is a submit button or image, this attribute is a name or keyword indicating where to display the response that is received by submitting the form. This is a name of, or keyword for, a browsing context (e.g. tab, window, or inline frame). This attribute overrides the {{htmlattrxref("target", "form")}} attribute of the elements's form owner. The following keywords have special meanings: +
    +
  • _self: Load the response into the same browsing context as the current one. This is the default if the attribute is not specified.
  • +
  • _blank: Load the response into a new unnamed browsing context.
  • +
  • _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • +
  • _top: Load the response into the top-level browsing context (i.e. the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.
  • +
+
+
{{htmlattrdef("height")}} {{HTMLVersionInline("5")}}
+
If the value of the type attribute is image, defines the height of the image displayed for the button in pixels.
+
{{htmlattrdef("inputmode")}} {{HTMLVersionInline("5")}}
+
A hint to browsers for which virtual keyboard to display. This attribute applies when the the type attribute is text, password, email, or url. Possible values: +
    +
  • none: No virtual keyboard should be displayed.
  • +
  • text: Text input in the user's locale.
  • +
  • decimal: Fractional numeric input.
  • +
  • numeric: Numeric input.
  • +
  • tel: Telephone input, including asterisk and pound key. Prefer <input type="tel">.
  • +
  • search: A virtual keyboard optimized for search input.
  • +
  • email: Email input. Prefer <input type="email">.
  • +
  • url: URL input. Prefer <input type="url">.
  • +
+ +
+
Spec conflict: The WHATWG spec lists inputmode, and modern browsers are working towards supporting it. The W3C HTML 5.2 spec however no longer lists it (i.e. marks it as obsolete). You should consider the WHATWG definition as correct, until a consensus is reached.
+
+
+
{{htmlattrdef("list")}} {{HTMLVersionInline("5")}}
+
Points to a {{HTMLElement("datalist")}} of predefined options to suggest to the user. The value must be the id of a <datalist> element in the same document. Browsers display only valid options for the input. This attribute is ignored when the type attribute is hidden, checkbox, radio, file, or a button type.
+
{{htmlattrdef("max")}} {{HTMLVersionInline("5")}}
+
The maximum (numeric or date-time) value for the input. Must not be less than its minimum (min attribute) value.
+
{{htmlattrdef("maxlength")}}
+
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in UTF-16 code units) that the user can enter. For other control types, it is ignored.
+
{{htmlattrdef("min")}} {{HTMLVersionInline("5")}}
+
The minimum (numeric or date-time) value for this input, which must not be greater than its maximum (max attribute) value.
+
{{htmlattrdef("minlength")}} {{HTMLVersionInline("5")}}
+
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the minimum number of characters (in UTF-16 code points) that the user can enter. For other control types, it is ignored.
+
{{htmlattrdef("multiple")}} {{HTMLVersionInline("5")}}
+
This Boolean attribute indicates whether the user can enter more than one value. This attribute only applies when the type attribute is set to email or file.
+
{{htmlattrdef("name")}}
+
The name of the control, which is submitted with the control's value as part of the form data. If no name is specified or it is empty, the control's value is not submitted with the form.
+
{{htmlattrdef("pattern")}} {{HTMLVersionInline("5")}}
+
A regular expression that the control's value is checked against. The pattern must match the entire value. Use the title attribute to describe the pattern to help the user. This attribute only applies when the value of the type attribute is text, search, tel, url, email, or password. The regular expression language is the same as the JavaScript {{jsxref("RegExp")}} algorithm, with the 'u' parameter that makes it treat the pattern as a sequence of unicode code points. The pattern is not surrounded by forward slashes.
+
{{htmlattrdef("placeholder")}} {{HTMLVersionInline("5")}}
+
A hint to the user of what can be entered in the control, typically in the form of an example of the type of information that should be entered. The placeholder text must not contain carriage returns or line-feeds. +
Note: Before using placeholder, please see the section {{anch("Labels and placeholders")}} to ensure that you use them correctly if at all. Placeholders can be confusing and can disrupt certain operations in unexpected ways.
+
+
{{htmlattrdef("readonly")}} {{HTMLVersionInline("5")}}
+
This Boolean attribute prevents the user from modifying the value of the input. It is ignored if the value of the type attribute is hidden, range, color, checkbox, radio, file, or a button type (such as button or submit).
+
{{htmlattrdef("required")}} {{HTMLVersionInline("5")}}
+
This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The {{cssxref(":optional")}} and {{cssxref(":required")}} CSS pseudo-classes will be applied to the field as appropriate.
+
{{htmlattrdef("size")}}
+
The initial size of the control. Starting in HTML5, this attribute applies only when the type attribute is set to text, search, tel, url, email, or password, otherwise it is ignored. The size must be an integer greater than zero. The default value is 20.
+
HTML5 states "the user agent should ensure that at least that many characters are visible", but different characters have different widths in certain fonts. In some browsers, a certain string with x characters will not be entirely visible even if size is defined as x.
+
{{htmlattrdef("spellcheck")}} {{HTMLVersionInline("5")}}
+
Setting the value of this attribute to true indicates that the element needs to have its spelling and grammar checked. The value default indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck value. The value false indicates that the element should not be checked.
+
{{htmlattrdef("src")}}
+
If the value of the type attribute is image, this attribute specifies the URL of the image file to display on the graphical submit button.
+
{{htmlattrdef("step")}} {{HTMLVersionInline("5")}}
+
Works with the min and max attributes to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this attribute is not set to any, the control accepts only values at multiples of the step value greater than the minimum.
+
{{htmlattrdef("tabindex")}} element-specific in {{HTMLVersionInline(4)}}, global in {{HTMLVersionInline("5")}}
+
The position of the element in the tabbing navigation order for the current document.
+
{{htmlattrdef("usemap")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline", "HTML5")}}
+
The name of a {{HTMLElement("map")}} element to be used as an image map.
+
{{htmlattrdef("value")}}
+
The initial value of the control. This attribute is optional except when the value of the type attribute is radio or checkbox.
+
When reloading the page, Firefox and IE will ignore the value specified in the HTML source, if the value was changed before the reload.
+
{{htmlattrdef("width")}} {{HTMLVersionInline("5")}}
+
If the value of the type attribute is image, this attribute defines the width of the image displayed for the button in pixels.
+
+ +

Non-standard <input> attributes

+ +
+
{{htmlattrdef("autocorrect")}} {{non-standard_inline}}
+
This is a non-standard attribute supported by Safari that is used to control whether autocorrection should be enabled when the user is entering/editing the text value of the <input>. Possible attribute values are: +
    +
  • on: Enable autocorrection.
  • +
  • off: Disable autocorrection.
  • +
+ autocorrect documentation in the Safari HTML Reference.
+
{{htmlattrdef("incremental")}} {{non-standard_inline}}
+
This is a nonstandard attribute supported by WebKit (Safari) and Blink (Chrome) that only applies when the type is search. If the attribute is present, regardless of what its value is, the <input> fires search events as the user edits the text value. The event is only fired after an implementation-defined timeout has elapsed since the most recent keystroke, and new keystrokes reset the timeout. In other words, the event firing is debounced. If the attribute is absent, the search event is only fired when the user explicitly initiates a search (e.g. by pressing the Enter key while within field). incremental documentation in the Safari HTML Reference
+
{{htmlattrdef("mozactionhint")}} {{non-standard_inline}}
+
Specifies an "action hint" used to determine how to label the enter key on mobile devices with virtual keyboards. Supported values are go, done, next, search, and send. These automatically get mapped to the appropriate string and are case-insensitive.
+
{{htmlattrdef("results")}} {{non-standard_inline}}
+
This is a nonstandard attribute supported by Safari that only applies when the type is search. It is used to control the maximum number of entries that should be displayed in the <input>'s native dropdown list of past search queries. Its value should be a nonnegative decimal integer.
+
{{htmlattrdef("webkitdirectory")}} {{non-standard_inline}}
+
This Boolean attribute indicates if the selector used when the type attribute is file has to allow for the selection of directories only.
+
{{htmlattrdef("x-moz-errormessage")}} {{non-standard_inline}}
+
This Mozilla extension allows you to specify the error message to display when a field doesn't successfully validate.
+
+ +

Styling input elements

+ +

You can style <input> elements using various color-related attributes in particular. One unusual one that is specific to text entry-related elements is the CSS {{cssxref("caret-color")}} property, which lets you set the color used to draw the text input caret:

+ +

HTML

+ +
<label for="textInput">Note the red caret:</label>
+<input id="textInput" class="custom" size="32"/>
+
+ +

CSS

+ +
input.custom {
+  caret-color: red;
+  font: 16px "Helvetica", "Arial", "sans-serif"
+}
+
+ +

Result

+ +

{{EmbedLiveSample('Styling_input_elements', 500, 80)}}

+ +

For more information about adding color to elements in HTML, see Applying color to HTML elements using CSS.

+ +

Labels and placeholders

+ +
+

TL;DR: To save you time, here's the key point: don't use the {{htmlattrxref("placeholder", "input")}} attribute if you can avoid it. If you need to label an <input> element, use the {{HTMLElement("label")}} element.

+
+ +

There are three seemingly similar ways to associate assistive text with an <input>. However, they are actually quite different, and only one of them is always a good choice. Here we will look at each of them and learn best practices for providing the user with guidance when entering data into a form.

+ +

The <label> element

+ +

The {{HTMLElement("label")}} element is the only way to provide explanatory information about a form field that is always appropriate (aside from any layout concerns you have). It's never a bad idea to use a <label> to explain what should be entered into an <input> or {{HTMLElement("textarea")}}.

+ +

The placeholder attribute

+ +

The {{htmlattrxref("placeholder", "input")}} attribute lets you specify a prompt that appears within the <input> element's content area itself when empty. It's intended to be used to show an example input, rather than an explanation or prompt, but tends to be badly misused.

+ +

Here are two inputs that take a password, each with a placeholder:

+ +

Example of correct and incorrect placeholder usage

+ +

The first one uses a placeholder string "MyGr8P@sswrd", demonstrating what a password might look like. And no, that's not really a great password.

+ +

The second one uses a prompt string, "Enter your password" as a placeholder. The first, and most obvious, problem with doing this is that as soon as the user types their first character, they no longer have a prompt explaining what that field is for.

+ +

That's why, instead, you should use the {{HTMLElement("label")}} element. The placeholder should never be required in order to understand your forms. While some people are able to remember what a given empty box is meant for after its only identifying text vanishes, others cannot.

+ +

If the user can't understand your form if the placeholders are missing (say, in a browser that doesn't support placeholder, or in the case above where the user starts typing then gets confused), you're not using placeholders properly.

+ +

In addition, browsers with automatic page translation features may skip over attributes when translating. That means the placeholder may not get translated, resulting in important information not being translated.

+ +

If you feel like you need to use a placeholder, it's possible to use both a placeholder and a label:

+ +

+ + + +

Unadorned text adjacent to the <input> element

+ +

You can also just have plain text adjacent to the <input> element, like this:

+ +
<p>Enter your name: <input id="name" type="text" size="30"></p>
+ +

Please don't do this. This doesn't create a relationship between the prompt and the <input> element, which is important for reasons we'll get into in the next section.

+ +

Why you should use labels

+ +

In addition to the information provided above, there are a number of other reasons why <label> is the best way to explain <input>s:

+ + + +

Examples

+ +

You can find multiple examples of <input> element usage on the pages covering each individual type — see {{anch("Form <input> types")}}, and also see the {{anch("Live example")}} at the top of the article.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'forms.html#the-input-element', '<input>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML Media Capture', '#the-capture-attribute','<input capture>')}}{{Spec2('HTML Media Capture')}}Adds the capture element
{{SpecName('HTML5 W3C', 'forms.html#the-input-element', '<input>')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('HTML4.01', 'interact/forms.html#h-17.4', '<form>')}}{{Spec2('HTML4.01')}} 
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.input")}}

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.7")}}{{CompatVersionUnknown}}1.01.0
type="time"20{{CompatVersionUnknown}}{{CompatGeckoDesktop(57)}}{{CompatNo}}10.62{{CompatNo}}[1]
accept{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}10{{CompatUnknown}}{{CompatNo}}
mozactionhint{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("2.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
autocapitalize43{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [3]
autofocus, max, min, pattern, placeholder, required, step, list, multiple5.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}109.65.0
captureChrome for Android (0.16){{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
fakepath added to file input values{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
form10{{CompatVersionUnknown}}4{{CompatNo}}[7]9.55.0
formaction, formenctype, formmethod, formnovalidate, formtarget9.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}1010.625.1
incremental{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
inputmode{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
minlength40.0{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
readonly1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.7")}}6[2] 1.01.0
spellcheck10.0{{CompatNo}}{{CompatGeckoDesktop("1.9.2")}}1011.04.0
webkitdirectory{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("49.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
type="time"{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(57)}}{{CompatNo}}10.62{{CompatVersionUnknown}}[1]
accept{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocapitalize{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
autofocus, max, min, pattern, placeholder, required, step, list, multiple{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[5]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
capture3.0{{CompatNo}}{{CompatGeckoMobile("10.0")}}{{CompatUnknown}}{{CompatUnknown}}6.0
fakepath added to file input values{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile("53")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
form, formaction, formenctype, formmethod, formnovalidate, formtarget{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
minlength{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}27.0{{CompatUnknown}}
spellcheck{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}11.0{{CompatUnknown}}
webkitdirectory{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("49.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] It is recognized but there is no UI.

+ +

[2] Missing for type="checkbox" and type="radio".

+ +

[3] In Safari autocapitalize="words" capitalizes every word's second character.

+ +

[4] datetime has been removed from the spec and browsers in favour of datetime-local.

+ +

[5] see {{bug(1355389)}}

+ +

[6] Not yet implemented. For progress, see {{bug("888320")}} and TPE DOM/Date time input types.

+ +

Notes

+ +

File inputs

+ +
    +
  1. +

    Starting in {{Gecko("2.0")}}, calling the click() method on an <input> element of type file opens the file picker and lets the user select files. See Using files from web applications for an example and more details.

    +
  2. +
  3. +

    You cannot set the value of a file picker from a script — doing something like the following has no effect:

    + +
    var e = getElementById("someFileInputElement");
    +e.value = "foo";
    +
    +
  4. +
  5. +

    When a file is chosen using an <input type="file">, the real path to the source file is not shown in the input's value attribute for obvious security reasons. Instead, the filename is shown, with C:\fakepath\ appended to the beginning of it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is defined in the spec.

    +
  6. +
+ +

Error messages

+ +

If you want Firefox to present a custom error message when a field fails to validate, you can use the x-moz-errormessage attribute to do so:

+ +
<input type="email"
+ x-moz-errormessage="Please specify a valid email address.">
+
+ +

Note, however, that this is not standard and will not have an effect on other browsers.

+ +

Localization

+ +

The allowed inputs for certain <input> types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.

+ +

Firefox uses the following heuristics to determine the locale to validate the user's input (at least for type="number"):

+ + + +

Using mozactionhint on Firefox mobile

+ +

You can use the {{htmlattrxref("mozactionhint", "input")}} attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a "Next" label, you can do this:

+ +
<input type="text" mozactionhint="next">
+
+ +

The result is:

+ +

+ +

Note the "Next" key in the lower-right corner of the keyboard.

+ +

See also

+ + diff --git a/files/uk/web/html/index.html b/files/uk/web/html/index.html new file mode 100644 index 0000000000..3f865c915a --- /dev/null +++ b/files/uk/web/html/index.html @@ -0,0 +1,91 @@ +--- +title: HTML +slug: Web/HTML +tags: + - HTML + - HTML5 + - Landing + - WWW + - Гіпертекст + - Довідка +translation_of: Web/HTML +--- +
{{HTMLSidebar()}}
+ +

Мова гіпертекстової розмітки (HyperText Markup Language — HTML) використовується для створення і візуального відображення веб-сторінок.

+ +

Основу кожної веб-сторінки в мережі Інтернет становить HTML. Під терміном «гіпертекст» мається на увазі текст, сформований за допомогою мови розмітки і який містить гіперпосилання, якими зв'язані веб-сторінки одна з одною, роблячи Всесвітню павутину тим, чим вона є сьогодні. Створюючи і публікуючи веб-сторінки в мережі Інтернет, ви стаєте активними учасниками Всесвітньої павутини. HTML підтримує як візуальні зображення, так і інший медіаконтент. HTML є мовою, що описує структуру і семантику вмісту веб-документу. Контент веб-сторінки розмічений за допомогою тегів, що представляють HTML-елементи. Прикладами таких елементів є {{HTMLElement("head")}}, {{HTMLElement("title")}}, {{HTMLElement("body")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("p")}}, {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("img")}}, {{HTMLElement("picture")}}, і т.д. Ці елементи формують будівельні блоки для будь-якого веб-сайта.

+ +

Статті, представлені тут, містять довідкові матеріали з веб-розробки.

+ +
+ + +
+

Бажаєте стати веб-розробником фронтенду?

+ +

Ми уклали повний курс, що включає в себе всю необхідну інформацію задля досягнення вашої мети.

+ +

Розпочати

+
+ +

Довідники

+ +
+
Блокові елементи
+
В HTML (мові гіпертекстової розмітки — Hypertext Markup Language) елементи бувають блокові або рядкові. Блокові елементи займають всю ширину батьківського елемента (контейнера), таким чином утворюючи блок. У цій статті пояснюється, як це працює. 
+
CORS: включені зображення
+
Специфікації HTML вводять атрибут crossorigin, що разом з відповідним заголовком CORS дозволяють використовувати зображення через елемент <img> і завантаженому з інших джерел зображенням бути використаним в canvas так, як наче вони завантажуються з поточного джерела.
+
CORS: налаштування атрибутів
+
В HTML5, деякі HTML-елементи, що підтримують CORS, такі як <img> або <video>, мають crossorigin атрибут (crossOrigin властивості), який дозволяє налаштувати запити CORS для отриманих даних елемента.
+
Контроль правопису в формах HTML
+
Firefox 2 вводить підтримку перевірки правопису в текстових полях та полях веб-форм. Користувач може вказати використання інтерфейсу about:config незалежно від того, чи ввімкнено перевірку правопису, і чи потрібно перевіряти обидва текстові поля, чи лише текстові області.
+
DASH Адаптивний потік для HTML 5 відео
+
Dynamic Adaptive Streaming over HTTP (DASH) - це адаптивний потоковий (трансляційний) протокол. Це означає, що він дозволяє потоку відеозв'язку (трансляції) переключатися між швидкістю передачі даних (бітрейтом) на основі пропускної здатності мережі, щоб продовжувати відтворення відео.
+
Управління фокусом в HTML
+
В робочому проекті HTML5 activeElement DOM атрибут та hasFocus() DOM метод дають програмісту можливість кращого контролю інтерактивності сторінки в результаті дій користувача. Наприклад, обидва вони можуть бути використані для складання статистики, відстеження кількості кліків на певних посиланнях сторінки, вимірювання часу, протягом якого активний елемент тощо. Крім того, у поєднанні з технологією AJAX, вони допомагають мінімізувати кількість запитів на сервер в залежності від активності користувача та розмітки сторінки.
+
Глобальні атрибути
+
Глобальні атрибути можуть бути вказані на всіх елементах HTML, навіть тих, які не вказані в стандарті . Це означає, що будь-які нестандартні елементи, як і раніше, повинні дозволити ці атрибути, навіть якщо використання цих елементів означає, що документ більше не відповідає стандарту HTML5. Наприклад, HTML5-сумісні браузери приховують вміст, позначений як <foo hidden>...<foo>, хоча <foo> не є дійсним елементом HTML.
+
Довідка по HTML атрибутам
+
Елементи в HTML мають атрибути; це додаткові значення, які налаштовують елементи або регулюють їх поведінку різними способами для задоволення критеріїв, які хочуть користувачі.
+
Довідка по HTML елементам
+
Ця сторінка містить усі HTML елементи.
+
Довідка по HTML
+
HTML - це мова, яка описує структуру та семантичний вміст веб-документа; він складається з елементів, кожен з яких може бути змінений деякою кількістю атрибутів.
+
Рядкові елементи
+
В HTML (мові гіпертекстової розмітки — Hypertext Markup Language) елементи бувають блокові або рядкові. Рядковий елемент займає стільки місця в рядку, скільки вимагає розмір самого елемента, і його вплив обмежується тегами, які цей елемент визначають. Приклади у цій статті пояснюють, як працюють рядкові елементи.
+
Типи посилань
+
У HTML наступні типи посилань вказують на зв'язок між двома документами, в яких одне посилання на інше використовується за допомогою елемента <a>, <area>, або <link>.
+
Медіа формати, що підтримуються аудіо та відео елементами HTML
+
Елементи <audio> та <video> надають підтримку для відтворення аудіо та відео матеріалів, не вимагаючи плагінів.
+
Мікроформати
+
Мікроформати (іноді використовується абревіатура μF) - це невеликі шаблони HTML для позначення таких об'єктів, як люди, організації, події, місця розташування, публікації в блозі, продукти, огляди, резюме, рецепти тощо.
+ Вони є простими для вставки семантики в HTML і швидко надають API, який буде використовуватися пошуковими системами, агрегаторами та іншими інструментами.
+
Оптимізація ваших сторінок для спекулятивного парсингу (аналізу)
+
Традиційно в браузерах HTML-парсер (аналізатор) працює на головній гілці і блокується після тега </script> доки сценарій не буде завантажено з мережі і не виконано. HTML парсер в Firefox 4 і новіших підтримує спекулятивний синтаксичний аналіз поза головної гілки. Він продовжує парсити, доки скрипти завантажуються і виконуються. Як і в Firefox 3.5 та 3.6, HTML парсер починає спекулятивні завантаження скриптів, стилів і зображень, коли він знаходить їх у початку потоку. Проте в Firefox 4 і новіше HTML-парсер також спекулятивно виконує алгоритм побудови дерева HTML . Та коли спекуляція (відстежування) вдається, немає необхідності переробляти частину вхідного файлу, який вже був сканований на скрипти, стилі та зображення. Недоліком є те, що більше роботи втрачається, коли спекуляція (відстежування) зазнала невдачі.
+
Використання кешу додатків
+
HTML5 забезпечує механізм кешування додатків, який дозволяє веб-додаткам працювати в автономному режимі. Розробники можуть використовувати інтерфейс Application Cache (AppCache) щоб вказати ресурси, які браузер повинен кешувати та зробити доступними для офлайн-користувачів. Додатки, які кешують завантаження, працюють коректно, навіть якщо користувачі клікають кнопку оновлення, коли вони знаходяться офлайн.
+
+ +

Переглянути все...

+ +
+

Інструкції та посібники

+ +
+
Інструкція з HTML для розробників
+
Статті MDN, що демонструють конкретні методи, які ви можете використовувати при створенні веб-контенту за допомогою HTML, а також навчальні посібники та інші матеріали, які можуть бути вам корисними. Довідник може містити редакційні уроки, поради та інформацію щодо розробки HTML.
+
+
+
diff --git a/files/uk/web/html/inline_elements/index.html b/files/uk/web/html/inline_elements/index.html new file mode 100644 index 0000000000..908a9b6263 --- /dev/null +++ b/files/uk/web/html/inline_elements/index.html @@ -0,0 +1,79 @@ +--- +title: Рядкові елементи +slug: Web/HTML/Inline_elements +tags: + - HTML +translation_of: Web/HTML/Inline_elements +--- +

Вступ

+ +

В HTML (мові гіпертекстової розмітки — Hypertext Markup Language) елементи бувають блокові або рядкові. Рядковий елемент займає стільки місця в рядку, скільки вимагає розмір самого елемента, і його вплив обмежується тегами, які цей елемент визначають. Приклади у цій статті пояснюють, як працюють рядкові елементи.

+ +

Приклад рядкового елемента

+ +

HTML

+ +
<p>Цей <span>span</span> є рядковим елементом; колір його бекграунда змінений, щоб показати початок і кінець елемента.</p>
+ +

CSS

+ +
span { background-color: #8ABB55; }
+
+ +

{{ EmbedLiveSample('Inline_example') }}

+ +

Рядкові vs. блокові

+ +
+
Модель контенту
+
Зазвичай рядкові елементи можуть містити лише дані та інші рядкові елементи.
+
Форматування
+
За замовчуванням, рядкові елементи не починаються з нового рядка.
+
+ +

Елементи

+ +

Ці елементи є рядковими:

+ +
+
+
{{ HTMLElement("a") }}
+
{{ HTMLElement("b") }}
+
{{ HTMLElement("big") }}
+
{{ HTMLElement("i") }}
+
{{ HTMLElement("small") }}
+
{{ HTMLElement("tt") }}
+
{{ HTMLElement("abbr") }}
+
{{ HTMLElement("acronym") }}
+
{{ HTMLElement("cite") }}
+
{{ HTMLElement("code") }}
+
{{ HTMLElement("dfn") }}
+
{{ HTMLElement("em") }}
+
{{ HTMLElement("kbd") }}
+
{{ HTMLElement("strong") }}
+
{{ HTMLElement("samp") }}
+
{{ HTMLElement("time") }}
+
{{ HTMLElement("var") }}
+
{{ HTMLElement("bdo") }}
+
{{ HTMLElement("br") }}
+
{{ HTMLElement("img") }}
+
{{ HTMLElement("map") }}
+
{{ HTMLElement("object") }}
+
{{ HTMLElement("q") }}
+
{{ HTMLElement("script") }}
+
{{ HTMLElement("span") }}
+
{{ HTMLElement("sub") }}
+
{{ HTMLElement("sup") }}
+
{{ HTMLElement("button") }}
+
{{ HTMLElement("input") }}
+
{{ HTMLElement("label") }}
+
{{ HTMLElement("select") }}
+
{{ HTMLElement("textarea") }}
+
+
+ +

Також дивися

+ + diff --git "a/files/uk/web/html/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" "b/files/uk/web/html/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" new file mode 100644 index 0000000000..2e4425a878 --- /dev/null +++ "b/files/uk/web/html/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" @@ -0,0 +1,27 @@ +--- +title: HTML довідник +slug: Web/HTML/Довідник +tags: + - HTML + - Landing + - WWW + - Довідка +translation_of: Web/HTML/Reference +--- +
{{HTMLSidebar}}
+ +

Цей HTML-довідник описує всі елементи і атрибути HTML, включаючи глобальні атрибути, які застосовуються до всіх елементів.

+ +
+
+
Довідник HTML елементів
+
This page lists all the HTML elements.
+
Довідник HTML атрибутів
+
Elements in HTML have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want.
+
Глобальні атрибути
+
Global attributes may be specified on all HTML elements, even those not specified in the standard. That means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer HTML5-compliant. For example, HTML5-compliant browsers hide content marked as <foo hidden>...<foo>, even though <foo> is not a valid HTML element.
+
Типи посиланнь
+
In HTML, the following link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, or <link> element.
+
+ +

Переглянути всі сторінки помічені "HTML"...

diff --git "a/files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/html/index.html" "b/files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/html/index.html" new file mode 100644 index 0000000000..22489d772f --- /dev/null +++ "b/files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/html/index.html" @@ -0,0 +1,169 @@ +--- +title: +slug: Web/HTML/Елемент/html +tags: + - Корінь + - Структура +translation_of: Web/HTML/Element/html +--- +

{{HTMLRef}}

+ +

HTML-елемент <html> являє собою корінь HTML-документа. Решта елементів мають бути його нащадками.

+ +

Оскільки <html> є першим (за винятком коментарів) елементом документа, він зветься кореневим елементом. І хоча цей тег може бути відсутнім для {{glossary("HTML")}}, в {{glossary("XHTML")}} він має бути відкритий і закритий явно.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Категорії вмістуВідсутні.
Дозволений вмістОдин елемент {{HTMLElement("head")}} та один (наступний за ним) елемент {{HTMLElement("body")}}.
Обов'язковість тегів +

Початковий тег можна опустити, якщо перша річ всередині елементу <html> — не коментар. Кінцевий тег можна опустити тоді, коли одразу після елементу <html> немає коментаря, і він містить елемент {{HTMLElement("body")}}, що має або вміст (непустий), або початковий тег.

+
Дозволені пращуриЯк кореневий елемент документа, або як піддокумент складного документа там, де це дозволено.
Інтерфейс DOM{{domxref("HTMLHtmlElement")}}
+ +

Атрибути

+ +

Цей елемент має глобальні атрибути.

+ +
+
{{htmlattrdef("manifest")}} {{obsolete_inline}}
+
Вказує URI manifest-файлу, що позначає ресурси, які підлягають локальному кешуванню. Детальніше див. Using the application cache.
+
{{htmlattrdef("version")}} {{obsolete_inline}}
+
Вказує версію HTML {{glossary("DTD", "Document Type Definition")}}  цього документа. Цей атрибут визнано застарілим, вживайте !DOCTYPE замість нього.
+
{{htmlattrdef("xmlns")}} 
+
Вказує простір імен (XML) документа. Типове значення "http://www.w3.org/1999/xhtml". Для XHTML то обов'язковий атрибут, а для HTML може бути відсутнім.
+
+ +

Приклад

+ +
+

Використаний в прикладі  {{glossary("DOCTYPE")}} вказує на {{glossary("HTML5")}}.

+
+ +
<!DOCTYPE html>
+<html>
+  <head>...</head>
+  <body>...</body>
+</html>
+
+ +

Специфікації

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-html-element', '<html>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'semantics.html#the-html-element', '<html>')}}{{Spec2('HTML5 W3C')}}Додано підтримку атрибута manifest (згодом визнаний застарілим).
+ Атрибут version визнано застарілим.
{{SpecName('HTML4.01', 'struct/global.html#h-7.3', '<html>')}}{{Spec2('HTML4.01')}}Атрибут version визнано застарілим.
+ +

Підтримка браузерами

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
manifest{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
manifest{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Див. також

+ + diff --git "a/files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/iframe/index.html" "b/files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/iframe/index.html" new file mode 100644 index 0000000000..fc5b06a037 --- /dev/null +++ "b/files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/iframe/index.html" @@ -0,0 +1,260 @@ +--- +title: '