Content categories - HTML: HyperText Markup Language

Content categories
==================

Most HTML elements are a member of one or more **content categories** — these categories group elements that share common characteristics. This is a loose grouping (it doesn't actually create a relationship among elements of these categories), but they help define and describe the categories' shared behavior and their associated rules, especially when you come upon their intricate details. It's also possible for elements to not be a member of *any* of these categories.

There are three types of content categories:

* Main content categories, which describe common rules shared by many elements.
* Form-related content categories, which describe rules common to form-related elements.
* Specific content categories, which describe rare categories shared only by a few elements, sometimes only in a specific context.

**Note:** A more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the relevant portions of the HTML specification.

![A Venn diagram showing how the various content categories interrelate. The following sections explain these relationships in text.](/en-US/docs/Web/HTML/Content_categories/content_categories_venn.png)

Main content categories
-----------------------

### Metadata content

Elements belonging to the *metadata content* category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other *out-of-band* information.

Elements belonging to this category are `<base>`, `<link>`, `<meta>`, `<noscript>`, `<script>`, `<style>` and `<title>`.

### Flow content

Flow content is a broad category that encompasses most elements that can go inside the `<body>` element, including heading elements, sectioning elements, phrasing elements, embedding elements, interactive elements, and form-related elements. It also includes text nodes (but not those that only consist of white space characters).

The flow elements are:

* `<a>`
* `<abbr>`
* `<address>`
* `<article>`
* `<aside>`
* `<audio>`
* `<b>`
* `<bdo>`
* `<bdi>`
* `<blockquote>`
* `<br>`
* `<button>`
* `<canvas>`
* `<cite>`
* `<code>`
* `<data>`
* `<datalist>`
* `<del>`
* `<details>`
* `<dfn>`
* `<dialog>`
* `<div>`
* `<dl>`
* `<em>`
* `<embed>`
* `<fieldset>`
* `<figure>`
* `<footer>`
* `<form>`
* `<h1>`-`<h6>`
* `<header>`
* `<hgroup>`
* `<hr>`
* `<i>`
* `<iframe>`
* `<img>`
* `<input>`
* `<ins>`
* `<kbd>`
* `<label>`
* `<main>`
* `<map>`
* `<mark>`
* `<math>`
* `<menu>`
* `<meter>`
* `<nav>`
* `<noscript>`
* `<object>`
* `<ol>`
* `<output>`
* `<p>`
* `<picture>`
* `<pre>`
* `<progress>`
* `<q>`
* `<ruby>`
* `<s>`
* `<samp>`
* `<search>`
* `<script>`
* `<section>`
* `<select>`
* `<slot>`
* `<small>`
* `<span>`
* `<strong>`
* `<sub>`
* `<sup>`
* `<svg>`
* `<table>`
* `<template>`
* `<textarea>`
* `<time>`
* `<u>`
* `<ul>`
* `<var>`
* `<video>`
* `<wbr>`
* plain text

A few other elements belong to this category, but only if a specific condition is fulfilled:

* `<area>`, if it is a descendant of a `<map>` element
* `<link>`, if the itemprop attribute is present
* `<meta>`, if the itemprop attribute is present
* `<style>`, if the `scoped`
Deprecated
 attribute is present
### Sectioning content

Sectioning content, a subset of flow content, creates a section in the current outline defining the scope of `<header>` elements, `<footer>` elements, and heading content.

Elements belonging to this category are `<article>`, `<aside>`, `<nav>`, and `<section>`.

### Heading content

Heading content, a subset of flow content, defines the title of a section. This definition applies both to sections marked by an explicit sectioning content elements and to those implicitly defined by the heading content itself.

Elements belonging to this category are `<h1>`-`<h6>` and `<hgroup>`.

**Note:** Though likely to contain heading content, the `<header>` is not heading content itself.

**Note:** The `<hgroup>` element is not recommended as it does not work properly with assistive technologies. It was removed from the W3C HTML specification prior to HTML 5 being finalized, but is still part of the WHATWG specification and is at least partially supported by most browsers.

### Phrasing content

Phrasing content, a subset of flow content, refers to the text and the markup within a document. Sequences of phrasing content make up paragraphs.

Elements belonging to this category are:

* `<abbr>`
* `<audio>`
* `<b>`
* `<bdi>`
* `<bdo>`
* `<br>`
* `<button>`
* `<canvas>`
* `<cite>`
* `<code>`
* `<data>`
* `<datalist>`
* `<dfn>`
* `<em>`
* `<embed>`
* `<i>`
* `<iframe>`
* `<img>`
* `<input>`
* `<kbd>`
* `<label>`
* `<mark>`
* `<math>`
* `<meter>`
* `<noscript>`
* `<object>`
* `<output>`
* `<picture>`
* `<progress>`
* `<q>`
* `<ruby>`
* `<s>`
* `<samp>`
* `<script>`
* `<select>`
* `<slot>`
* `<small>`
* `<span>`
* `<strong>`
* `<sub>`
* `<sup>`
* `<svg>`
* `<template>`
* `<textarea>`
* `<time>`
* `<u>`
* `<var>`
* `<video>`
* `<wbr>`
* plain text (including more than just whitespace characters)

A few other elements belong to this category, but only if a specific condition is fulfilled:

* `<a>`, if it contains only phrasing content
* `<area>`, if it is a descendant of a `<map>` element
* `<del>`, if it contains only phrasing content
* `<ins>`, if it contains only phrasing content
* `<link>`, if the itemprop attribute is present
* `<map>`, if it contains only phrasing content
* `<meta>`, if the itemprop attribute is present
### Embedded content

Embedded content, a subset of flow content, imports another resource or inserts content from another markup language or namespace into the document. Elements that belong to this category include:

* `<audio>`
* `<canvas>`
* `<embed>`
* `<iframe>`
* `<img>`
* `<math>`
* `<object>`
* `<picture>`
* `<svg>`
* `<video>`
### Interactive content

Interactive content, a subset of flow content, includes elements that are specifically designed for user interaction. Elements that belong to this category include:

* `<button>`
* `<details>`
* `<embed>`
* `<iframe>`
* `<label>`
* `<select>`
* `<textarea>`

Some elements belong to this category only under specific conditions:

* `<a>`, if the `href` attribute is present
* `<audio>`, if the `controls` attribute is present
* `<img>`, if the `usemap` attribute is present
* `<input>`, if the type attribute is not in the hidden state
* `<object>`, if the `usemap` attribute is present
* `<video>`, if the `controls` attribute is present
### Palpable content

Content is palpable when it's neither empty nor hidden; it is content that is rendered and is substantive. Elements whose model is flow content should have at least one node which is palpable.

### Form-associated content

Form-associated content is a subset of flow content comprising elements that have a form owner, exposed by a **form** attribute, and can be used everywhere flow content is expected. A form owner is either the containing `<form>` element or the element whose id is specified in the **form** attribute.

* `<button>`
* `<fieldset>`
* `<input>`
* `<label>`
* `<meter>`
* `<object>`
* `<output>`
* `<progress>`
* `<select>`
* `<textarea>`

This category contains several sub-categories:

listed

Elements that are listed in the `form.elements` and `fieldset.elements` collections. Contains `<button>`, `<fieldset>`, `<input>`, `<object>`, `<output>`, `<select>`, and `<textarea>`.

labelable

Elements that can be associated with `<label>` elements. Contains `<button>`, `<input>`, `<meter>`, `<output>`, `<progress>`, `<select>`, and `<textarea>`.

submittable

Elements that can be used for constructing the form data set when the form is submitted. Contains `<button>`, `<input>`, `<object>`, `<select>`, and `<textarea>`.

resettable

Elements that can be affected when a form is reset. Contains `<input>`, `<output>`, `<select>`, and `<textarea>`.

Secondary content categories
----------------------------

There are some secondary classifications of elements that can be useful to be aware of as well.

### Script-supporting elements

**Script-supporting elements** are elements which don't directly contribute to the rendered output of a document. Instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts.

The script-supporting elements are:

* `<script>`
* `<template>`
Transparent content model
-------------------------

If an element has a transparent content model, then its contents must be structured such that they would be valid HTML 5, even if the transparent element were removed and replaced by the child elements.

For example, the `<del>` and `<ins>` elements are transparent:

```html
<p>
  We hold these truths to be <del><em>sacred & undeniable</em></del>
  <ins>self-evident</ins>.
</p>
```

If those elements were removed, this fragment would still be valid HTML (if not correct English).

```html
<p>We hold these truths to be <em>sacred & undeniable</em> self-evident.</p>
```


Viewport meta tag - HTML: HyperText Markup Language

Viewport meta tag
=================

This article describes how to use the "viewport" `<meta>` tag to control the viewport's size and shape.

Background
----------

The browser's viewport is the area of the window in which web content can be seen. This is often not the same size as the rendered page, in which case the browser provides scrollbars for the user to scroll around and access all the content.

Some mobile devices and other narrow screens render pages in a virtual window or viewport, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once. Users can then zoom and pan to look more closely at different areas of the page. For example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space.

This is done because not all pages are optimized for mobile and break (or at least look bad) when rendered at a small viewport width. This virtual viewport is a way to make non-mobile-optimized sites in general look better on narrow screen devices.

However, this mechanism is not so good for pages that are optimized for narrow screens using media queries — if the virtual viewport is 980px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques. The viewport `<meta>` element mitigates this problem of virtual viewport on narrow screen devices.

Viewport basics
---------------

A typical mobile-optimized site contains something like the following:

```html
<meta name="viewport" content="width=device-width, initial-scale=1" />
```

Not all devices are the same width; you should make sure that your pages work well in a large variation of screen sizes and orientations.

The basic attributes of the "viewport" `<meta>` element include:

`width`

Controls the size of the viewport. It can be set to a specific number of pixels like `width=600` or to the special value `device-width`, which is 100vw, or 100% of the viewport width. Minimum: `1`. Maximum: `10000`. Negative values: ignored.

`height`

Controls the size of the viewport. It can be set to a specific number of pixels like `height=400` or to the special value `device-height`, which is 100vh, or 100% of the viewport height. Minimum: `1`. Maximum: `10000`. Negative values: ignored.

`initial-scale`

Controls the zoom level when the page is first loaded. Minimum: `0.1`. Maximum: `10`. Default: `1`. Negative values: ignored.

`minimum-scale`

Controls how much zoom out is allowed on the page. Minimum: `0.1`. Maximum: `10`. Default: `0.1`. Negative values: ignored.

`maximum-scale`

Controls how much zoom in is allowed on the page. Any value less than 3 fails accessibility. Minimum: `0.1`. Maximum: `10`. Default: `10`. Negative values: ignored.

`user-scalable`

Controls whether zoom in and zoom out actions are allowed on the page. Valid values: `0`, `1`, `yes`, or `no`. Default: `1`, which is the same as `yes`. Setting the value to `0`, which is the same as `no`, is against Web Content Accessibility Guidelines (WCAG).

`interactive-widget`

Specifies the effect that interactive UI widgets, such as a virtual keyboard, have on the page's viewports. Valid values: `resizes-visual`, `resizes-content`, or `overlays-content`. Default: `resizes-visual`.

**Warning:** Usage of `user-scalable=no` can cause accessibility issues to users with visual impairments such as low vision. WCAG requires a minimum of 2× scaling; however, the best practice is to enable a 5× zoom.

Screen density
--------------

Screen resolutions have risen to the size that individual pixels are indistinguishable by the human eye. For example, smartphones often have small screens with resolutions upwards of 1920–1080 pixels (≈400dpi). Because of this, many browsers can display their pages in a smaller physical size by translating multiple hardware pixels for each CSS "pixel". Initially, this caused usability and readability problems on many touch-optimized websites.

On high dpi screens, pages with `initial-scale=1` will effectively be zoomed by browsers. Their text will be smooth and crisp, but their bitmap images may not take advantage of the full screen resolution. To get sharper images on these screens, web developers may want to design images – or whole layouts – at a higher scale than their final size and then scale them down using CSS or viewport properties.

The default pixel ratio depends on the display density. On a display with density less than 200dpi, the ratio is 1.0. On displays with density between 200 and 300dpi, the ratio is 1.5. For displays with density over 300dpi, the ratio is the integer floor (*density*/150dpi). Note that the default ratio is true only when the viewport scale equals 1. Otherwise, the relationship between CSS pixels and device pixels depends on the current zoom level.

Viewport width and screen width
-------------------------------

Sites can set their viewport to a specific size. For example, the definition `"width=320, initial-scale=1"` can be used to fit precisely onto a small phone display in portrait mode. This can cause problems when the browser renders a page at a larger size. To fix this, browsers will expand the viewport width if necessary to fill the screen at the requested scale. This is especially useful on large-screen devices.

For pages that set an initial or maximum scale, this means the `width` property actually translates into a *minimum* viewport width. For example, if your layout needs at least 500 pixels of width then you can use the following markup. When the screen is more than 500 pixels wide, the browser will expand the viewport (rather than zoom in) to fit the screen:

```html
<meta name="viewport" content="width=500, initial-scale=1" />
```

Other attributes that are available are `minimum-scale`, `maximum-scale`, and `user-scalable`. These properties affect the initial scale and width, as well as limiting changes in zoom level.

The effect of interactive UI widgets
------------------------------------

Interactive UI widgets of the browser can influence the size of the page's viewports. The most common such UI widget is a virtual keyboard. To control which resize behavior the browser should use, set the `interactive-widget` property.

Allowed values are:

`resizes-visual`

The visual viewport gets resized by the interactive widget.

`resizes-content`

The viewport gets resized by the interactive widget.

`overlays-content`

Neither the viewport nor the visual viewport gets resized by the interactive widget.

When the viewport gets resized, the initial containing block also gets resized, thereby affecting the computed size of viewport units.

Common viewport sizes for mobile and tablet devices
---------------------------------------------------

If you want to know what mobile and tablet devices have which viewport widths, there is a comprehensive list of mobile and tablet viewport sizes here. This gives information such as viewport width on portrait and landscape orientation as well as physical screen size, operating system and the pixel density of the device.

Specifications
--------------

| Specification |
| --- |
| CSS Viewport Module Level 1 # viewport-meta |

See also
--------

* Article: Prepare for viewport resize behavior changes coming to Chrome on Android


Date and time formats used in HTML - HTML: HyperText Markup Language

Date and time formats used in HTML
==================================

Certain HTML elements use date and/or time values. The formats of the strings that specify these values are described in this article.

Elements that use such formats include certain forms of the `<input>` element that let the user choose or specify a date, time, or both, as well as the `<ins>` and `<del>` elements, whose `datetime` attribute specifies the date or date and time at which the insertion or deletion of content occurred.

For `<input>`, the values of `type` that return a `value` which contains a string representing a date and/or time are:

* `date`
* `datetime-local`
* `month`
* `time`
* `week`
Examples
--------

Before getting into the intricacies of how date and time strings are written and parsed in HTML, here are some examples that should give you a good idea what the more commonly-used date and time string formats look like.

Example HTML date and time strings| String | Date and/or time |
| --- | --- |
| `2005-06-07` | June 7, 2005 | [details] |
| `08:45` | 8:45 AM | [details] |
| `08:45:25` | 8:45 AM and 25 seconds | [details] |
| `0033-08-04T03:40` | 3:40 AM on August 4, 33 | [details] |
| `1977-04-01T14:00:30` | 30 seconds after 2:00 PM on April 1, 1977 | [details] |
| `1901-01-01T00:00Z` | Midnight UTC on January 1, 1901 | [details] |
| `1901-01-01T00:00:01-04:00` | 1 second past midnight Eastern Standard Time (EST) on January 1, 1901 | [details] |

Basics
------

Before looking at the various formats of date and time related strings used by HTML elements, it is helpful to understand a few fundamental facts about the way they're defined. HTML uses a variation of the ISO 8601 standard for its date and time strings. It's worth reviewing the descriptions of the formats you're using in order to ensure that your strings are in fact compatible with HTML, as the HTML specification includes algorithms for parsing these strings that is actually more precise than ISO 8601, so there can be subtle differences in how date and time strings are expected to look.

### Character set

Dates and times in HTML are always strings which use the ASCII character set.

### Year numbers

In order to simplify the basic format used for date strings in HTML, the specification requires that all years be given using the modern (or **proleptic**) Gregorian calendar. While user interfaces may allow entry of dates using other calendars, the underlying value always uses the Gregorian calendar.

While the Gregorian calendar wasn't created until the year 1582 (replacing the similar Julian calendar), for HTML's purposes, the Gregorian calendar is extended back to the year 1 C.E. Make sure any older dates account for this.

For the purposes of HTML dates, years are always at least four digits long; years prior to the year 1000 are padded with leading zeroes ("`0`"), so the year 72 is written as `0072`. Years prior to the year 1 C.E. are not supported, so HTML doesn't support years 1 B.C.E. (1 B.C.) or earlier.

A year is normally 365 days long, except during **leap years**.

#### Leap years

A **leap year** is any year which is divisible by 400 *or* the year is divisible by 4 but not by 100. Although the calendar year is normally 365 days long, it actually takes the planet Earth approximately 365.2422 days to complete a single orbit around the sun. Leap years help to adjust the calendar to keep it synchronized with the actual position of the planet in its orbit. Adding a day to the year every four years essentially makes the average year 365.25 days long, which is close to correct.

The adjustments to the algorithm (taking a leap year when the year can be divided by 400, and skipping leap years when the year is divisible by 100) help to bring the average even closer to the correct number of days (365.2425 days). Scientists occasionally add leap seconds to the calendar (seriously) to handle the remaining three ten-thousandths of a day and to compensate for the gradual, naturally occurring slowing of Earth's rotation.

While month `02`, February, normally has 28 days, it has 29 days in leap years.

### Months of the year

There are 12 months in the year, numbered 1 through 12. They are always represented by a two-digit ASCII string whose value ranges from `01` through `12`. See the table in the section Days of the month for the month numbers and their corresponding names (and lengths in days).

### Days of the month

Month numbers 1, 3, 5, 7, 8, 10, and 12 are 31 days long. Months 4, 6, 9, and 11 are 30 days long. Month 2, February, is 28 days long most years, but is 29 days long in leap years. This is detailed in the following table.

The months of the year and their lengths in days| Month number | Name (English) | Length in days |
| --- | --- | --- |
| 01 | January | 31 |
| 02 | February | 28 (29 in leap years) |
| 03 | March | 31 |
| 04 | April | 30 |
| 05 | May | 31 |
| 06 | June | 30 |
| 07 | July | 31 |
| 08 | August | 31 |
| 09 | September | 30 |
| 10 | October | 31 |
| 11 | November | 30 |
| 12 | December | 31 |

Week strings
------------

A week string specifies a week within a particular year. A **valid week string** consists of a valid year number, followed by a hyphen character ("`-`", or U+002D), then the capital letter "`W`" (U+0057), followed by a two-digit week of the year value.

The week of the year is a two-digit string between `01` and `53`. Each week begins on Monday and ends on Sunday. That means it's possible for the first few days of January to be considered part of the previous week-year, and for the last few days of December to be considered part of the following week-year. The first week of the year is the week that contains the *first Thursday of the year*. For example, the first Thursday of 1953 was on January 1, so that week—beginning on Monday, December 29—is considered the first week of the year. Therefore, December 30, 1952 occurs during the week `1953-W01`.

A year has 53 weeks if:

* The first day of the calendar year (January 1) is a Thursday **or**
* The first day of the year (January 1) is a Wednesday and the year is a leap year

All other years have 52 weeks.

| Week string | Week and year (Date range) |
| --- | --- |
| `2001-W37` | Week 37, 2001 (September 10-16, 2001) |
| `1953-W01` | Week 1, 1953 (December 29, 1952-January 4, 1953) |
| `1948-W53` | Week 53, 1948 (December 27, 1948-January 2, 1949) |
| `1949-W01` | Week 1, 1949 (January 3-9, 1949) |
| `0531-W16` | Week 16, 531 (April 13-19, 531) |
| `0042-W04` | Week 4, 42 (January 21-27, 42) |

Note that both the year and week numbers are padded with leading zeroes, with the year padded to four digits and the week to two.

Month strings
-------------

A month string represents a specific month in time, rather than a generic month of the year. That is, rather than representing "January," an HTML month string represents a month and year paired, like "January 1972."

A **valid month string** consists of a valid year number (a string of at least four digits), followed by a hyphen character ("`-`", or U+002D), followed by a two-digit numeric month number, where `01` represents January and `12` represents December.

| Month string | Month and year |
| --- | --- |
| `17310-09` | September, 17310 |
| `2019-01` | January, 2019 |
| `1993-11` | November, 1993 |
| `0571-04` | April, 571 |
| `0001-07` | July, 1 C.E. |

Notice that all years are at least four characters long; years that are fewer than four digits long are padded with leading zeroes.

Date strings
------------

A valid date string consists of a month string, followed by a hyphen character ("`-`", or U+002D), followed by a two-digit day of the month.

| Date string | Full date |
| --- | --- |
| `1993-11-01` | November 1, 1993 |
| `1066-10-14` | October 14, 1066 |
| `0571-04-22` | April 22, 571 |
| `0062-02-05` | February 5, 62 |

Time strings
------------

A time string can specify a time with precision to the minute, second, or to the millisecond. Specifying only the hour or minute isn't permitted. A **valid time string** minimally consists of a two-digit hour followed by a colon ("`:`", U+003A), then a two-digit minute. The minute may optionally be followed by another colon and a two-digit number of seconds. Milliseconds may be specified, optionally, by adding a decimal point character ("`.`", U+002E) followed by one, two, or three digits.

There are some additional basic rules:

* The hour is always specified using the 24-hour clock, with `00` being midnight and 11 PM being `23`. No values outside the range `00` – `23` are permitted.
* The minute must be a two-digit number between `00` and `59`. No values outside that range are allowed.
* If the number of seconds is omitted (to specify a time accurate only to the minute), no colon should follow the number of minutes.
* If specified, the integer portion of the number of seconds must be between `00` and `59`. You *cannot* specify leap seconds by using values like `60` or `61`.
* If the number of seconds is specified and is an integer, it must not be followed by a decimal point.
* If a fraction of a second is included, it may be from one to three digits long, indicating the number of milliseconds. It follows the decimal point placed after the seconds component of the time string.

| Time string | Time |
| --- | --- |
| `00:00:30.75` | 12:00:30.75 AM (30.75 seconds after midnight) |
| `12:15` | 12:15 PM |
| `13:44:25` | 1:44:25 PM (25 seconds after 1:44 PM) |

Local date and time strings
---------------------------

A valid `datetime-local` string consists of a `date` string and a `time` string concatenated together with either the letter "`T`" or a space character separating them. No information about the time zone is included in the string; the date and time is presumed to be in the user's local time zone.

When you set the `value` of a `datetime-local` input, the string is **normalized** into a standard form. Normalized `datetime` strings always use the letter "`T`" to separate the date and the time, and the time portion of the string is as short as possible. This is done by leaving out the seconds component if its value is `:00`.

 Examples of valid
 `datetime-local`
 strings
 | Date/time string | Normalized date/time string | Actual date and time |
| --- | --- | --- |
| `1986-01-28T11:38:00.01` | `1986-01-28T11:38:00.01` | January 28, 1986 at 11:38:00.01 AM |
| `1986-01-28 11:38:00.010` | `1986-01-28T11:38:00.01`

 Note that after normalization, this is the same string as the previous
 `datetime-local` string. The space has been replaced with
 the "`T`" character and the trailing zero in the fraction
 of a second has been removed to make the string as short as possible.
  | January 28, 1986 at 11:38:00.01 AM |
| `0170-07-31T22:00:00` | `0170-07-31T22:00`

 Note that the normalized form of this date drops the
 "`:00`" indicating the number of seconds to be zero,
 because the seconds are optional when zero, and the normalized string
 minimizes the length of the string.
  | July 31, 170 at 10:00 PM |

Global date and time strings
----------------------------

A global date and time string specifies a date and time as well as the time zone in which it occurs. A **valid global date and time string** is the same format as a local date and time string, except it has a time zone string appended to the end, following the time.

### Time zone offset string

A time zone offset string specifies the offset in either a positive or a negative number of hours and minutes from the standard time base. There are two standard time bases, which are very close to the same, but not exactly the same:

* For dates after the establishment of Coordinated Universal Time (UTC) in the early 1960s, the time base is `Z` and the offset indicates a particular time zone's offset from the time at the prime meridian at 0º longitude (which passes through the Royal Observatory at Greenwich, England).
* For dates prior to UTC, the time base is instead expressed in terms of UT1, which is the contemporary Earth solar time at the prime meridian.

The time zone string is appended immediately following the time in the date and time string. You can specify "`Z`" as the time zone offset string to indicate that the time is specified in UTC. Otherwise, the time zone string is constructed as follows:

1. A character indicating the sign of the offset: the plus character ("`+`", or U+002B) for time zones to the east of the prime meridian or the minus character ("`-`", or U+002D) for time zones to the west of the prime meridian.
2. A two-digit number of hours that the time zone is offset from the prime meridian. This value must be between `00` and `23`.
3. An optional colon ("`:`") character.
4. A two-digit number of minutes past the hour; this value must be between `00` and `59`.

While this format allows for time zones between -23:59 and +23:59, the current range of time zone offsets is -12:00 to +14:00, and no time zones are currently offset from the hour by anything other than `00`, `30`, or `45` minutes. This may change at more or less anytime, since countries are free to tamper with their time zones at any time and in any way they wish to do so.

Examples of valid global date and time strings| Global date and time string | Actual global date and time | Date and time at prime meridian |
| --- | --- | --- |
| `2005-06-07T00:00Z` | June 7, 2005 at midnight UTC | June 7, 2005 at midnight |
| `1789-08-22T12:30:00.1-04:00` |
 August 22, 1789 at a tenth of a second past 12:30 PM Eastern Daylight
 Time (EDT)
  | August 22, 1789 at a tenth of a second past 4:30 PM |
| `3755-01-01 00:00+10:00` | January 1, 3755 at midnight Australian Eastern Standard Time (AEST) | December 31, 3754 at 2:00 PM |

Date issues
-----------

Because of data storage and precision issues, you may want to be aware of a few client-side and server-side issues.

### The Y2K38 Problem (often server-side)

JavaScript uses double precision floating points to store dates, as with all numbers, meaning that JavaScript code will not suffer from the Y2K38 problem unless integer coercion/bit-hacks are used because all JavaScript bit operators use 32-bit signed 2s-complement integers.

The problem is with the server side of things: storage of dates greater than 2^31 - 1. To fix this problem, you must store all dates using either unsigned 32-bit integers, signed 64-bit integers, or double-precision floating points on the server. If your server is written in PHP, the fix may be as simple as upgrading to PHP 8 or 7, and upgrading your hardware to x86\_64 or IA64. If you are stuck with other hardware, you can try to emulate 64-bit hardware inside a 32-bit virtual machine, but most VMs don't support this kind of virtualization, since stability may suffer, and performance will definitely suffer greatly.

### The Y10k Problem (often client-side)

In many servers, dates are stored as numbers instead of as strings--numbers of a fixed size and agnostic of format (aside from endianness). After the year 10,000, those numbers will just be a bit bigger than before, so many servers will not see issues with forms submitted after the year 10,000.

The problem is with the client side of things: parsing of dates with more than 4 digits in the year.

```html
<!--midnight of January 1st, 10000: the exact time of Y10K-->
<input type="datetime-local" value="+010000-01-01T05:00" />
```

It's that simple. Just prepare your code for any number of digits. Do not only prepare for 5 digits. Here is JavaScript code for programmatically setting the value:

```js
function setValue(element, date) {
  const isoString = date.toISOString();
  element.value = isoString.substring(0, isoString.indexOf("T") + 6);
}
```

Why worry about the Y10K problem if it is going to happen many centuries after your death? Exactly because you will already be dead, so the companies using your software will be stuck using your software without any other coder who knows the system well enough to come in and fix it.

See also
--------

* `<input>`
* `<ins>` and `<del>`: see the `datetime` attribute, which specifies either a date or a local date and time at which the content was inserted or deleted
* The ISO 8601 specification
* Numbers and Dates in the JavaScript Guide
* The JavaScript `Date` object
* The `Intl.DateTimeFormat` object for formatting dates and times for a given locale


Constraint validation - HTML: HyperText Markup Language

Constraint validation
=====================

The creation of web forms has always been a complex task. While marking up the form itself is easy, checking whether each field has a valid and coherent value is more difficult, and informing the user about the problem may become a headache. HTML5 introduced new mechanisms for forms: it added new semantic types for the `<input>` element and *constraint validation* to ease the work of checking the form content on the client side. Basic, usual constraints can be checked, without the need for JavaScript, by setting new attributes; more complex constraints can be tested using the Constraint Validation API.

For a basic introduction to these concepts, with examples, see the Form validation tutorial.

**Note:** HTML Constraint validation doesn't remove the need for validation on the *server side*. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent such as by bad people trying to trick your web application. Therefore, you need to always also validate input constraints on the server side, in a way that is consistent with what is done on the client side.

Intrinsic and basic constraints
-------------------------------

In HTML, basic constraints are declared in two ways:

* By choosing the most semantically appropriate value for the `type` attribute of the `<input>` element, e.g., choosing the `email` type automatically creates a constraint that checks whether the value is a valid email address.
* By setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for JavaScript.
### Semantic input types

The intrinsic constraints for the `type` attribute are:

| Input type | Constraint description | Associated violation |
| --- | --- | --- |
| `<input type="URL">` | The value must be an absolute URL, as defined in the URL Living Standard. | **TypeMismatch** constraint violation |
| `<input type="email">` | The value must be a syntactically valid email address, which generally has the format `username@hostname.tld` but can also be local such as `username@hostname`. | **TypeMismatch** constraint violation |

For both of these input types, if the `multiple` attribute is set, several values can be set, as a comma-separated list. If any of these do not satisfy the condition described here, the **Type mismatch** constraint violation is triggered.

Note that most input types don't have intrinsic constraints, as some are barred from constraint validation or have a sanitization algorithm transforming incorrect values to a correct default.

### Validation-related attributes

In addition to the `type` attribute described above, the following attributes are used to describe basic constraints:

| Attribute | Input types supporting the attribute | Possible values | Constraint description | Associated violation |
| --- | --- | --- | --- | --- |
| `pattern` | `text`, `search`, `url`,
 `tel`, `email`, `password` |
 A
 JavaScript regular expression
 (compiled with the `global`, `ignoreCase`, and
 `multiline` flags *disabled*)
  | The value must match the pattern. | **`patternMismatch`**
 constraint violation
  |
| `min` | `range`, `number` | A valid number | The value must be greater than or equal to the value. | **`rangeUnderflow`**
 constraint violation
  |
| `date`, `month`, `week` | A valid date |
| `datetime-local`, `time` | A valid date and time |
| `max` | `range`, `number` | A valid number | The value must be less than or equal to the value | **`rangeOverflow`**
 constraint violation
  |
| `date`, `month`, `week` | A valid date |
| `datetime-local`, `time` | A valid date and time |
| `required` | `text`, `search`, `url`,
 `tel`, `email`, `password`,
 `date`, `datetime-local`,
 `month`, `week`, `time`,
 `number`, `checkbox`, `radio`,
 `file`; also on the `<select>` and
 `<textarea>` elements
  | *none* as it is a Boolean attribute: its presence means
 *true*, its absence means *false* | There must be a value (if set). | **`valueMissing`**
 constraint violation
  |
| `step` | `date` | An integer number of days |
 Unless the step is set to the `any` literal, the value must
 be **min** + an integral multiple of the step.
  | **`stepMismatch`**
 constraint violation
  |
| `month` | An integer number of months |
| `week` | An integer number of weeks |
| `datetime-local`, `time` | An integer number of seconds |
| `range`, `number` | An integer |
| `minlength` | `text`, `search`, `url`,
 `tel`, `email`, `password`; also on the
 `<textarea>` element
  | An integer length |
 The number of characters (code points) must not be less than the value
 of the attribute, if non-empty. All newlines are normalized to a single
 character (as opposed to CRLF pairs) for
 `<textarea>`.
  | **`tooShort`**
 constraint violation
  |
| `maxlength` | `text`, `search`, `url`,
 `tel`, `email`, `password`; also on the
 `<textarea>` element
  | An integer length |
 The number of characters (code points) must not exceed the value of the
 attribute.
  | **`tooLong`**
 constraint violation
  |

Constraint validation process
-----------------------------

Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the `<form>` element itself. The constraint validation is done in the following ways:

* By a call to the `checkValidity()` or `reportValidity()` method of a form-associated DOM interface, (`HTMLInputElement`, `HTMLSelectElement`, `HTMLButtonElement`, `HTMLOutputElement` or `HTMLTextAreaElement`), which evaluates the constraints only on this element, allowing a script to get this information. The `checkValidity()` method returns a Boolean indicating whether the element's value passes its constraints. (This is typically done by the user-agent when determining which of the CSS pseudo-classes, `:valid` or `:invalid`, applies.) In contrast, the `reportValidity()` method reports any constraint failures to the user.
* By a call to the `checkValidity()` or `reportValidity()` method on the `HTMLFormElement` interface.
* By submitting the form itself.

Calling `checkValidity()` is called *statically* validating the constraints, while calling `reportValidity()` or submitting the form is called *interactively* validating the constraints.

**Note:**

* If the `novalidate` attribute is set on the `<form>` element, interactive validation of the constraints doesn't happen.
* Calling the `submit()` method on the `HTMLFormElement` interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if it doesn't satisfy the constraints. Call the `click()` method on a submit button instead.

Complex constraints using the Constraint Validation API
-------------------------------------------------------

Using JavaScript and the Constraint API, it is possible to implement more complex constraints, for example, constraints combining several fields, or constraints involving complex calculations.

Basically, the idea is to trigger JavaScript on some form field event (like **onchange**) to calculate whether the constraint is violated, and then to use the method `field.setCustomValidity()` to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user.

### Constraint combining several fields: Postal code validation

The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like `D-` in Germany, `F-` in France or Switzerland), but some countries have postal codes with only a fixed number of digits; others, like the UK, have more complex structures, allowing letters at some specific positions.

**Note:** This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts.

As an example, we will add a script checking the constraint validation for this simple form:

```html
<form>
  <label for="ZIP">ZIP : </label>
  <input type="text" id="ZIP" />
  <label for="Country">Country : </label>
  <select id="Country">
    <option value="ch">Switzerland</option>
    <option value="fr">France</option>
    <option value="de">Germany</option>
    <option value="nl">The Netherlands</option>
  </select>
  <input type="submit" value="Validate" />
</form>
```

This displays the following form:

First, we write a function checking the constraint itself:

```js
function checkZIP() {
  // For each country, defines the pattern that the ZIP has to follow
  const constraints = {
    ch: [
      "^(CH-)?\\d{4}$",
      "Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950",
    ],
    fr: [
      "^(F-)?\\d{5}$",
      "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012",
    ],
    de: [
      "^(D-)?\\d{5}$",
      "Germany ZIPs must have exactly 5 digits: e.g. D-12345 or 12345",
    ],
    nl: [
      "^(NL-)?\\d{4}\\s\*([A-RT-Z][A-Z]|S[BCE-RT-Z])$",
      "Netherland ZIPs must have exactly 4 digits, followed by 2 letters except SA, SD and SS",
    ],
  };

  // Read the country id
  const country = document.getElementById("Country").value;

  // Get the NPA field
  const ZIPField = document.getElementById("ZIP");

  // Build the constraint checker
  const constraint = new RegExp(constraints[country][0], "");
  console.log(constraint);

  // Check it!
  if (constraint.test(ZIPField.value)) {
    // The ZIP follows the constraint, we use the ConstraintAPI to tell it
    ZIPField.setCustomValidity("");
  } else {
    // The ZIP doesn't follow the constraint, we use the ConstraintAPI to
    // give a message about the format required for this country
    ZIPField.setCustomValidity(constraints[country][1]);
  }
}
```

Then we link it to the **onchange** event for the `<select>` and the **oninput** event for the `<input>`:

```js
window.onload = () => {
  document.getElementById("Country").onchange = checkZIP;
  document.getElementById("ZIP").oninput = checkZIP;
};
```

### Limiting the size of a file before its upload

Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint Validation API, and especially the `field.setCustomValidity()` method, with another JavaScript API, here the File API.

Here is the HTML part:

```html
<label for="FS">Select a file smaller than 75 kB : </label>
<input type="file" id="FS" />
```

This displays:

The JavaScript reads the file selected, uses the `File.size()` method to get its size, compares it to the (hard coded) limit, and calls the Constraint API to inform the browser if there is a violation:

```js
function checkFileSize() {
  const FS = document.getElementById("FS");
  const files = FS.files;

  // If there is (at least) one file selected
  if (files.length > 0) {
    if (files[0].size > 75 \* 1024) {
      // Check the constraint
      FS.setCustomValidity("The selected file must not be larger than 75 kB");
      return;
    }
  }
  // No custom constraint violation
  FS.setCustomValidity("");
}
```

Finally, we hook the method with the correct event:

```js
window.onload = () => {
  document.getElementById("FS").onchange = checkFileSize;
};
```

Visual styling of constraint validation
---------------------------------------

Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.

### Controlling the look of elements

The look of elements can be controlled via CSS pseudo-classes.

#### :required and :optional CSS pseudo-classes

The `:required` and `:optional` pseudo-classes allow writing selectors that match form elements that have the `required` attribute, or that don't have it.

#### :placeholder-shown CSS pseudo-class

See `:placeholder-shown`.

#### :valid :invalid CSS pseudo-classes

The `:valid` and `:invalid` pseudo-classes are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly.

### Controlling the text of constraint violation

The following items can help with controlling the text of a constraint violation:

* The `setCustomValidity(message)` method on the following elements:
    + `<fieldset>`. Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers.
    + `<input>`
    + `<output>`
    + `<select>`
    + Submit buttons (created with either a `<button>` element with the `submit` type, or an `input` element with the submit type. Other types of buttons do not participate in constraint validation.
    + `<textarea>`
* The `ValidityState` interface describes the object returned by the `validity` property of the element types listed above. It represents various ways that an entered value can be invalid. Together, they help explain why an element's value fails to validate, if it's not valid.


HTML attribute: crossorigin - HTML: HyperText Markup Language

HTML attribute: crossorigin
===========================

The **`crossorigin`** attribute, valid on the `<audio>`, `<img>`, `<link>`, `<script>`, and `<video>` elements, provides support for CORS, defining how the element handles cross-origin requests, thereby enabling the configuration of the CORS requests for the element's fetched data. Depending on the element, the attribute can be a CORS settings attribute.

The `crossorigin` content attribute on media elements is a CORS settings attribute.

These attributes are enumerated, and have the following possible values:

`anonymous`

Request uses CORS headers and credentials flag is set to `'same-origin'`. There is no exchange of **user credentials** via cookies, client-side TLS certificates or HTTP authentication, unless destination is the same origin.

`use-credentials`

Request uses CORS headers, credentials flag is set to `'include'` and **user credentials** are always included.

`""`

Setting the attribute name to an empty value, like `crossorigin` or `crossorigin=""`, is the same as `anonymous`.

An invalid keyword and an empty string will be handled as the `anonymous` keyword.

By default (that is, when the attribute is not specified), CORS is not used at all. The user agent will not ask for permission for full access to the resource and in the case of a cross-origin request, certain limitations will be applied based on the type of element concerned:

|  |  |
| --- | --- |
| Element | Restrictions |
| `img`, `audio`, `video` | When resource is placed in `<canvas>`, element is marked as *tainted*. |
| `script` | Access to error logging via `window.onerror` will be limited. |
| `link` | Request with no appropriate `crossorigin` header may be discarded. |

**Note:** The `crossorigin` attribute is not supported for `rel="icon"` in Chromium-based browsers. See the open Chromium issue.

### Example: `crossorigin` with the `<script>` element

You can use the following `<script>` element to tell a browser to execute the `https://example.com/example-framework.js` script without sending user-credentials.

```html
<script
 src="https://example.com/example-framework.js"
 crossorigin="anonymous"></script>
```

### Example: Web manifest with credentials

The `use-credentials` value must be used when fetching a manifest that requires credentials, even if the file is from the same origin.

```html
<link rel="manifest" href="/app.webmanifest" crossorigin="use-credentials" />
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # cors-settings-attributes |

Browser compatibility
---------------------

### html.elements.img.crossorigin

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.link.crossorigin

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.script.crossorigin

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.video.crossorigin

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Cross-Origin Resource Sharing (CORS)
* HTML attribute: `rel`


HTML attribute: autocomplete - HTML: HyperText Markup Language

HTML attribute: autocomplete
============================

The HTML `autocomplete` attribute lets web developers specify what if any permission the user agent has to provide automated assistance in filling out form field values, as well as guidance to the browser as to the type of information expected in the field.

It is available on `<input>` elements that take a text or numeric value as input, `<textarea>` elements, `<select>` elements, and `<form>` elements.

The source of the suggested values is generally up to the browser; typically values come from past values entered by the user, but they may also come from pre-configured values. For instance, a browser might let the user save their name, address, phone number, and email addresses for autocomplete purposes. Perhaps the browser offers the ability to save encrypted credit card information, for autocompletion following an authentication procedure.

If an `<input>`, `<select>` or `<textarea>` element has no `autocomplete` attribute, then browsers use the `autocomplete` attribute of the element's form owner, which is either the `<form>` element that the element is a descendant of, or the `<form>` whose `id` is specified by the `form` attribute of the element (see the `<form>` `autocomplete` attribute).

**Note:** In order to provide autocompletion, user-agents might require `<input>`/`<select>`/`<textarea>` elements to:

1. Have a `name` and/or `id` attribute
2. Be descendants of a `<form>` element
3. The form to have a submit button

Try it
------

Values
------

"`off`"

The browser is not permitted to automatically enter or select a value for this field. It is possible that the document or application provides its own autocomplete feature, or that security concerns require that the field's value not be automatically entered.

**Note:** In most modern browsers, setting `autocomplete` to "`off`" will not prevent a password manager from asking the user if they would like to save username and password information, or from automatically filling in those values in a site's login form. See the autocomplete attribute and login fields.

"`on`"

The browser is allowed to automatically complete the input. No guidance is provided as to the type of data expected in the field, so the browser may use its own judgement.

"`name`"

The field expects the value to be a person's full name. Using "`name`" rather than breaking the name down into its components is generally preferred because it avoids dealing with the wide diversity of human names and how they are structured; however, you can use the following `autocomplete` values if you do need to break the name down into its components:

"`honorific-prefix`"

The prefix or title, such as "Mrs.", "Mr.", "Miss", "Ms.", "Dr.", or "Mlle.".

"`given-name`"

The given (or "first") name.

"`additional-name`"

The middle name.

"`family-name`"

The family (or "last") name.

"`honorific-suffix`"

The suffix, such as "Jr.", "B.Sc.", "PhD.", "MBASW", or "IV".

"`nickname`"

A nickname or handle.

"`email`"

An email address.

"`username`"

A username or account name.

"`new-password`"

A new password. When creating a new account or changing passwords, this should be used for an "Enter your new password" or "Confirm new password" field, as opposed to a general "Enter your current password" field that might be present. This may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password (see also Preventing autofilling with autocomplete="new-password").

"`current-password`"

The user's current password.

"`one-time-code`"

 A one-time password (OTP) for verifying user identity that is used as an additional factor in a sign-in flow.
 Most commonly this is a code received via some out-of-channel mechanism, such as SMS, email, or authenticator application.

"`organization-title`"

A job title, or the title a person has within an organization, such as "Senior Technical Writer", "President", or "Assistant Troop Leader".

"`organization`"

A company or organization name, such as "Acme Widget Company" or "Girl Scouts of America".

"`street-address`"

A street address. This can be multiple lines of text, and should fully identify the location of the address within its second administrative level (typically a city or town), but should not include the city name, ZIP or postal code, or country name.

"`shipping`"

The street address to send the product. This can be combined with other tokens, such as "`shipping street-address`" and "`shipping address-level2`".

"`billing`"

The street address to associate with the form of payment used. This can be combined with other tokens, such as "`billing street-address`" and "`billing address-level2`".

"`address-line1`", "`address-line2`", "`address-line3`"

Each individual line of the street address. These should only be present if the "`street-address`" is not present.

"`address-level4`"

The finest-grained administrative level, in addresses which have four levels.

"`address-level3`"

The third administrative level, in addresses with at least three administrative levels.

"`address-level2`"

The second administrative level, in addresses with at least two of them. In countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located.

"`address-level1`"

The first administrative level in the address. This is typically the province in which the address is located. In the United States, this would be the state. In Switzerland, the canton. In the United Kingdom, the post town.

"`country`"

A country or territory code.

"`country-name`"

A country or territory name.

"`postal-code`"

A postal code (in the United States, this is the ZIP code).

"`cc-name`"

The full name as printed on or associated with a payment instrument such as a credit card. Using a full name field is preferred, typically, over breaking the name into pieces.

"`cc-given-name`"

A given (first) name as given on a payment instrument like a credit card.

"`cc-additional-name`"

A middle name as given on a payment instrument or credit card.

"`cc-family-name`"

A family name, as given on a credit card.

"`cc-number`"

A credit card number or other number identifying a payment method, such as an account number.

"`cc-exp`"

A payment method expiration date, typically in the form "MM/YY" or "MM/YYYY".

"`cc-exp-month`"

The month in which the payment method expires.

"`cc-exp-year`"

The year in which the payment method expires.

"`cc-csc`"

The security code for the payment instrument; on credit cards, this is the 3-digit verification number on the back of the card.

"`cc-type`"

The type of payment instrument (such as "Visa" or "Master Card").

"`transaction-currency`"

The currency in which the transaction is to take place.

"`transaction-amount`"

The amount, given in the currency specified by "`transaction-currency`", of the transaction, for a payment form.

"`language`"

A preferred language, given as a valid BCP 47 language tag.

"`bday`"

A birth date, as a full date.

"`bday-day`"

The day of the month of a birth date.

"`bday-month`"

The month of the year of a birth date.

"`bday-year`"

The year of a birth date.

"`sex`"

A gender identity (such as "Female", "Fa'afafine", "Hijra", "Male", "Nonbinary"), as freeform text without newlines.

"`tel`"

A full telephone number, including the country code. If you need to break the phone number up into its components, you can use these values for those fields:

"`tel-country-code`"

The country code, such as "1" for the United States, Canada, and other areas in North America and parts of the Caribbean.

"`tel-national`"

The entire phone number without the country code component, including a country-internal prefix. For the phone number "1-855-555-6502", this field's value would be "855-555-6502".

"`tel-area-code`"

The area code, with any country-internal prefix applied if appropriate.

"`tel-local`"

The phone number without the country or area code. This can be split further into two parts, for phone numbers which have an exchange number and then a number within the exchange. For the phone number "555-6502", use "`tel-local-prefix`" for "555" and "`tel-local-suffix`" for "6502".

"`tel-extension`"

A telephone extension code within the phone number, such as a room or suite number in a hotel or an office extension in a company.

"`impp`"

A URL for an instant messaging protocol endpoint, such as "xmpp:username@example.net".

"`url`"

A URL, such as a home page or company website address as appropriate given the context of the other fields in the form.

"`photo`"

The URL of an image representing the person, company, or contact information given in the other fields in the form.

"`webauthn`"

Passkeys generated by the Web Authentication API, as requested by a conditional `navigator.credentials.get()` call (i.e., one that includes `mediation: 'conditional'`). See Sign in with a passkey through form autofill for more details.

See the WHATWG Standard for more detailed information.

**Note:** The `autocomplete` attribute also controls whether Firefox will — unlike other browsers — persist the dynamic disabled state and (if applicable) dynamic checkedness of an `<input>` element, `<textarea>` element, or entire `<form>` across page loads. The persistence feature is enabled by default. Setting the value of the `autocomplete` attribute to `off` disables this feature. This works even when the `autocomplete` attribute would normally not apply by virtue of its `type`. See Firefox bug 654072.

Examples
--------

```html
<div>
  <label for="cc-number">Enter your credit card number</label>
  <input name="cc-number" id="cc-number" autocomplete="off" />
</div>
```

Administrative levels in addresses
----------------------------------

The four administrative level fields (`address-level1` through `address-level4`) describe the address in terms of increasing levels of precision within the country in which the address is located. Each country has its own system of administrative levels, and may arrange the levels in different orders when addresses are written.

`address-level1` always represents the broadest administrative division; it is the least-specific portion of the address short of the country name.

### Form layout flexibility

Given that different countries write their address in different ways, with each field in different places within the address, and even different sets and numbers of fields entirely, it can be helpful if, when possible, your site is able to switch to the layout expected by your users when presenting an address entry form, given the country the address is located within.

### Variations

The way each administrative level is used will vary from country to country. Below are some examples; this is not meant to be an exhaustive list.

#### United States

A typical home address within the United States looks like this:

 432 Anywhere St
 Exampleville CA 95555

In the United States, the least-specific portion of the address is the state, in this case "CA" (the official US Postal Service shorthand for "California"). Thus `address-level1` is the state, or "CA" in this case.

The second-least specific portion of the address is the city or town name, so `address-level2` is "Exampleville" in this example address.

United States addresses do not use levels 3 and up.

#### United Kingdom

Address input forms in the UK should contain one address level and one, two or three address lines, depending on the address. A complete address would look like so:

 103 Frogmarch Street
 Upper-Wapping
 Winchelsea
 TN99 8ZZ

The address levels are:

* `address-level1`: The post town — "Winchelsea" in this case.
* `address-line2`: The locality — "Upper-Wapping" in this case.
* `address-line1`: The house/street particulars — "103 Frogmarch Street".

The postcode is separate. Note that you can actually use just the postcode and `address-line1` to successfully deliver mail in the UK, so they should be the only mandatory items, but usually people tend to provide more details.

#### China

China can use as many as three administrative levels: the province, the city, and the district.

The 6 digit postal code is not always needed but when supplied it is placed separately with a label for clarity. For example:

 北京市东城区建国门北大街 8 号华润大厦 17 层 1708 单元
 邮编：100005

#### Japan

An address in Japan is typically **written in one line**, in an order from the least-specific to more-specific portions (in **reverse order to the United States**). There are two or three administrative levels in an address. Additional line can be used to show building names and room numbers. The postal code is separate. For example:

 〒 381-0000
 長野県長野市某町 123

"〒" and following seven digits shows the postal code.

`address-level1` is used for prefectures or the Tokyo Metropolis; "長野県" (Nagano Prefecture) is in this case. `address-level2` is typically used for cities, counties, towns and villages; "長野市" (Nagano City) in this case. "某町 123" is `address-line1` which consists of an area name and a lot number.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # attr-fe-autocomplete |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `<input>` element
* The `<select>` element
* The `<textarea>` element
* The `<form>` element
* HTML forms
* All global attributes


HTML attribute: elementtiming - HTML: HyperText Markup Language

HTML attribute: elementtiming
=============================

The **`elementtiming`** attribute is used to indicate that an element is flagged for tracking by `PerformanceObserver` objects using the `"element"` type. For more details, see the `PerformanceElementTiming` interface.

This attribute may be applied to `<img>`, `<image>` elements inside an `<svg>`, poster images of `<video>` elements, elements which have a `background-image`, and elements containing text nodes, such as a `<p>`.

In the DOM, this attribute is reflected as `Element.elementTiming`.

Usage
-----

The value given for `elementtiming` becomes an identifier for the observed element.

```html
<img alt="alt" src="img.jpg" elementtiming="label for element" />
```

Good contenders for elements you might want to observe are:

* The main image for an article.
* A blog post title
* Images in a carousel for a shopping site.
* The poster image for the main video on a page.
Examples
--------

```html
<img alt="Alt for a main blog post image" src="my-massive-image.jpg" elementtiming="Main image">

<p elementtiming="important-text">Some very important information.</p">
```

See also
--------

* `PerformanceElementTiming`
* `Element.elementTiming`


HTML attribute: accept - HTML: HyperText Markup Language

HTML attribute: accept
======================

The **`accept`** attribute takes as its value a comma-separated list of one or more file types, or unique file type specifiers, describing which file types to allow.

Try it
------

Overview
--------

The accept property is an attribute of the file `<input>` type. It was supported on the `<form>` element, but was removed in favor of file.

Because a given file type may be identified in more than one manner, it's useful to provide a thorough set of type specifiers when you need files of specific type, or use the wild card to denote a type of any format is acceptable.

For instance, there are a number of ways Microsoft Word files can be identified, so a site that accepts Word files might use an `<input>` like this:

```html
<input
 type="file"
 id="docpicker"
 accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
```

Whereas if you're accepting a media file, you may want to be include any format of that media type:

```html
<input type="file" id="soundFile" accept="audio/\*" />
<input type="file" id="videoFile" accept="video/\*" />
<input type="file" id="imageFile" accept="image/\*" />
```

The `accept` attribute doesn't validate the types of the selected files; it provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

Because of this, you should make sure that expected requirement is validated server-side.

Examples
--------

When set on a file input type, the native file picker that opens up should only enable selecting files of the correct file type. Most operating systems lighten the files that don't match the criteria and aren't selectable.

```html
<p>
  <label for="soundFile">Select an audio file:</label>
  <input type="file" id="soundFile" accept="audio/\*" />
</p>
<p>
  <label for="videoFile">Select a video file:</label>
  <input type="file" id="videoFile" accept="video/\*" />
</p>
<p>
  <label for="imageFile">Select some images:</label>
  <input type="file" id="imageFile" accept="image/\*" multiple />
</p>
```

Note the last example allows you to select multiple images. See the `multiple` attribute for more information.

Unique file type specifiers
---------------------------

A **unique file type specifier** is a string that describes a type of file that may be selected by the user in an `<input>` element of type `file`. Each unique file type specifier may take one of the following forms:

* A valid case-insensitive filename extension, starting with a period (".") character. For example: `.jpg`, `.pdf`, or `.doc`.
* A valid MIME type string, with no extensions.
* The string `audio/*` meaning "any audio file".
* The string `video/*` meaning "any video file".
* The string `image/*` meaning "any image file".

The `accept` attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. For example, a file picker that needs content that can be presented as an image, including both standard image formats and PDF files, might look like this:

```html
<input type="file" accept="image/\*,.pdf" />
```

Using file inputs
-----------------

### A basic example

```html
<form method="post" enctype="multipart/form-data">
  <div>
    <label for="file">Choose file to upload</label>
    <input type="file" id="file" name="file" multiple />
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

```
div {
  margin-bottom: 10px;
}
```

This produces the following output:

**Note:** You can find this example on GitHub too — see the source code, and also see it running live.

Regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file.

Including the `multiple` attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down `Shift` or `Control`, and then clicking). If you only want the user to choose a single file per `<input>`, omit the `multiple` attribute.

### Limiting accepted file types

Often you won't want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG.

Acceptable file types can be specified with the `accept` attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples:

* `accept="image/png"` or `accept=".png"` — Accepts PNG files.
* `accept="image/png, image/jpeg"` or `accept=".png, .jpg, .jpeg"` — Accept PNG or JPEG files.
* `accept="image/*"` — Accept any file with an `image/*` MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.)
* `accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"` — accept anything that smells like an MS Word document.

Let's look at a more complete example:

```html
<form method="post" enctype="multipart/form-data">
  <div>
    <label for="profile\_pic">Choose file to upload</label>
    <input
 type="file"
 id="profile\_pic"
 name="profile\_pic"
 accept=".jpg, .jpeg, .png" />
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
```

```
div {
  margin-bottom: 10px;
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # attr-input-accept |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using files from web applications
* File API


HTML attribute: required - HTML: HyperText Markup Language

HTML attribute: required
========================

The Boolean **`required`** attribute, if present, indicates that the user must specify a value for the input before the owning form can be submitted.

The `required` attribute is supported by `text`, `search`, `url`, `tel`, `email`, `password`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `checkbox`, `radio`, `file`, `<input>` types along with the `<select>` and `<textarea>` form control elements. If present on any of these input types and elements, the `:required` pseudo class will match. If the attribute is not included, the `:optional` pseudo class will match.

The attribute is not supported or relevant to range and color, as both have default values. It is also not supported on hidden as it can not be expected that a user to fill out a form that is hidden. Nor is it supported on any of the button types, including `image`.

Note `color` and `range` don't support `required` as both always have a value. Type `color` defaults to `#000000`. The default for `range` is the midpoint between `min` and `max` — with `min` and `max` defaulting to 0 and 100 respectively in most browsers if not declared.

In the case of a same named group of radio buttons, if a single radio button in the group has the `required` attribute, a radio button in that group must be checked, although it doesn't have to be the one on which the attribute is applied. To improve code maintenance, it is recommended to either include the `required` attribute in every same-named radio button in the group, or else in none.

In the case of a same named group of checkbox input types, only the checkboxes with the `required` attribute are required.

**Note:** Setting `aria-required="true"` tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the element.

### Attribute interactions

Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified.

### Usability

When including the `required` attribute, provide a visible indication near the control informing the user that the `<input>`, `<select>` or `<textarea>` is required. In addition, target required form controls with the `:required` pseudo-class, styling them in a way to indicate they are required. This improves usability for sighted users. Assistive technology should inform the user that the form control is mandatory based on the required attribute, but adding `aria-required="true"` doesn't hurt, in case the browser / screen reader combination does not support `required` yet.

### Constraint validation

If the element is required and the element's value is the empty string, then the element is suffering from `valueMissing` and the element will match the `:invalid` pseudo class.

Accessibility concerns
----------------------

Provide an indication to users informing them the form control is required. Ensure the messaging is multi-faceted, such as through text, color, markings, and attribute, so that all users understand the requirements whether they have color blindness, cognitive differences, or are using a screen reader.

Example
-------

### HTML

```html
<form>
  <div class="group">
    <input type="text" />
    <label>Normal</label>
  </div>
  <div class="group">
    <input type="text" required />
    <label>Required</label>
  </div>
  <input type="submit" />
</form>
```

### Result

See also
--------

* `validityState.valueMissing`
* `:required` and `:optional`
* `<input>`
* `<select>`


HTML attribute: step - HTML: HyperText Markup Language

HTML attribute: step
====================

The **`step`** attribute is a number that specifies the granularity that the value must adhere to or the keyword `any`. It is valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types.

The `step` sets the *stepping interval* when clicking up and down spinner buttons, moving a slider left and right on a range, and validating the different date types. If not explicitly included, `step` defaults to 1 for `number` and `range`, and 1 unit type (minute, week, month, day) for the date/time input types. The value can must be a positive number - integer or float — or the special value `any`, which means no stepping is implied, and any value is allowed (barring other constraints, such as `min` and `max`).

The default stepping value for `number` inputs is 1, allowing only integers to be entered, *unless* the stepping base is not an integer. The default stepping value for `time` is 1 second, with 900 being equal to 15 minutes.

Syntax
------

Default values for step| Input type | Value | Example |
| --- | --- | --- |
| date | 1 (day) | `<input type="date" min="2019-12-25" step="1">` |
| month | 1 (month) | `<input type="month" min="2019-12" step="12">` |
| week | 1 (week) | `<input type="week" min="2019-W23" step="2">` |
| time | 60 (seconds) | `<input type="time" min="09:00" step="900">` |
| datetime-local | 1 (second) | `<input type="datetime-local" min="2019-12-25T19:30"
step="7">` |
| number | 1 | `<input type="number" min="0" step="0.1" max="10">` |
| range | 1 | `<input type="range" min="0" step="2" max="10">` |

If `any` is not explicitly set, valid values for the `number`, date/time input types, and `range` input types are equal to the basis for stepping - the `min` value and increments of the step value, up to the `max` value, if specified. For example, if we have `<input type="number" min="10" step="2">` any even integer, 10 or greater, is valid. If omitted, `<input type="number">`, any integer is valid, but floats, like 4.2, are not valid, as `step` defaults to 1. For 4.2 to be valid, `step` would have had to be set to `any`, 0.1, 0.2, or any the min value would have had to be a number ending in .2, such as `<input type="number" min="-5.2">`

### min impact on step

The value of `min` and `step` define what are valid values, even if the `step` attribute is not included, as `step` defaults to `0`.

We add a big red border around invalid inputs:

```css
input:invalid {
  border: solid red 3px;
}
```

Then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to 1.

```html
<input id="myNumber" name="myNumber" type="number" step="2" min="1.2" />
```

Valid values include `1.2`, `3.2`, `5.2`, `7.2`, `9.2`, `11.2`, and so on. Integers and even numbers followed by .2 are not valid. As we included an invalid value, supporting browsers will show the value as invalid. The number spinner, if present, will only show valid float values of `1.2` and greater

**Note:** When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in constraint validation and will match the `:invalid` and `:out-of-range` pseudoclasses

See Client-side validation and `stepMismatch` for more information.

Accessibility concerns
----------------------

Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `min` attribute, ensure this minimum requirement is understood by the user. Providing instructions within the `<label>` may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using `aria-labelledby` or `aria-describedby`.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # attr-input-step |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `max`
* `min`
* Constraint validation
* Form validation
* `validityState.stepMismatch`
* `:out-of-range`
* `<input>`
* date, month, week, time, datetime-local, number and range types, and the `<meter>`


HTML attribute: min - HTML: HyperText Markup Language

HTML attribute: min
===================

The **`min`** attribute defines the minimum value that is acceptable and valid for the input containing the attribute. If the `value` of the element is less than this, the element fails validation. This value must be less than or equal to the value of the `max` attribute.

Some input types have a default minimum. If the input has no default minimum and a value is specified for `min` that can't be converted to a valid number (or no minimum value is set), the input has no minimum value.

It is valid for the input types including: date, month, week, time, datetime-local, number and range types, and the `<meter>` element.

### Syntax

 Syntax for
 `min`
 values by input
 `type`
| Input type | Syntax | Example |
| --- | --- | --- |
| date | `yyyy-mm-dd` | `<input type="date" min="2019-12-25" step="1">` |
| month | `yyyy-mm` | `<input type="month" min="2019-12" step="12">` |
| week | `yyyy-W##` | `<input type="week" min="2019-W23" step="">` |
| time | `hh:mm` | `<input type="time" min="09:00" step="900">` |
| datetime-local | `yyyy-mm-ddThh:mm` | `<input type="datetime-local" min="2019-12-25T19:30">` |
| number | <number> | `<input type="number" min="0" step="5" max="100">` |
| range | <number> | `<input type="range" min="60" step="5" max="100">` |

**Note:** When the data entered by the user doesn't adhere to the min value set, the value is considered invalid in constraint validation and will match the `:invalid` and `:out-of-range` pseudo-classes.

See Client-side validation and `rangeUnderflow` for more information.

For the `<meter>` element, the `min` attribute defines the lower numeric bound of the measured range. This must be less than the minimum value (`max` attribute), if specified. In both cases, if omitted, the value defaults to 1.

 Syntax for
 `min`
 values for other elements
 | Input type | Syntax | Example |
| --- | --- | --- |
| `<meter>` | <number> | `<meter id="fuel" min="0" max="100" low="33" high="66"
optimum="80" value="40"> at 40/100</meter>` |

### Impact on step

The value of `min` and `step` define what are valid values, even if the `step` attribute is not included, as `step` defaults to `0`.

We add a big red border around invalid inputs:

```css
input:invalid {
  border: solid red 3px;
}
```

Then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to 1.

```html
<input id="myNumber" name="myNumber" type="number" min="7.2" value="8" />
```

Because `step` defaults to 1, valid values include `7.2`, `8.2`, `9.2`, and so on. The value 8 is not valid. As we included an invalid value, supporting browsers will show the value as invalid.

If not explicitly included, `step` defaults to 1 for `number` and `range`, and 1 unit type (second, week, month, day) for the date/time input types.

Accessibility concerns
----------------------

Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `min` attribute, ensure this minimum requirement is understood by the user. Providing instructions within the `<label>` may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using `aria-labelledby` or `aria-describedby`.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-min-and-max-attributes |
| HTML Standard # attr-meter-max |

Browser compatibility
---------------------

### html.elements.input.min

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.meter.min

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `step`
* `max`
* other meter attributes: `low`, `high`, `optimum`
* Constraint validation
* Form validation
* `validityState.rangeUnderflow`
* `:out-of-range`
* `<input>`
* date, month, week, time, datetime-local, number and range types, and the `<meter>`


HTML attribute: max - HTML: HyperText Markup Language

HTML attribute: max
===================

The **`max`** attribute defines the maximum value that is acceptable and valid for the input containing the attribute. If the `value` of the element is greater than this, the element fails validation. This value must be greater than or equal to the value of the `min` attribute. If the `max` attribute is present but is not specified or is invalid, no `max` value is applied. If the `max` attribute is valid and a non-empty value is greater than the maximum allowed by the `max` attribute, constraint validation will prevent form submission.

Valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, and both the `<progress>` and `<meter>` elements, the `max` attribute is a number that specifies the most positive value a form control to be considered valid.

If the value exceeds the max value allowed, the `validityState.rangeOverflow` will be true, and the control will be matched by the `:out-of-range` and `:invalid` pseudo-classes.

### Syntax

 Syntax for
 `max`
 values by input
 `type`
| Input type | Syntax | Example |
| --- | --- | --- |
| date | `yyyy-mm-dd` | `<input type="date" max="2019-12-25" step="1">` |
| month | `yyyy-mm` | `<input type="month" max="2019-12" step="12">` |
| week | `yyyy-W##` | `<input type="week" max="2019-W23" step="">` |
| time | `hh:mm` | `<input type="time" max="17:00" step="900">` |
| datetime-local | `yyyy-mm-ddThh:mm` | `<input type="datetime-local" max="2019-12-25T23:59">` |
| number | <number> | `<input type="number" min="0" step="5" max="100">` |
| range | <number> | `<input type="range" min="60" step="5" max="100">` |

**Note:** When the data entered by the user doesn't adhere to the maximum value set, the value is considered invalid in constraint validation and will match the `:invalid` and `:out-of-range` pseudo-classes.

See Client-side validation and `rangeOverflow` for more information.

For the `<progress>` element, the `max` attribute describes how much work the task indicated by the `progress` element requires. If present, must have a value greater than zero and be a valid floating point number. For the `<meter>` element, the `max` attribute defines the upper numeric bound of the measured range. This must be greater than the minimum value (`min` attribute), if specified. In both cases, if omitted, the value defaults to 1.

 Syntax for
 `max`
 values for other elements
 | Input type | Syntax | Example |
| --- | --- | --- |
| `<progress>` | <number> | `<progress id="file" max="100" value="70"> 70%
</progress>` |
| `<meter>` | <number> | `<meter id="fuel" min="0" max="100" low="33" high="66"
optimum="80" value="40"> at 40/100</meter>` |

Accessibility concerns
----------------------

Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `max` attribute, ensure this maximum requirement is understood by the user. Providing instructions within the `<label>` may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using `aria-labelledby` or `aria-describedby`.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-min-and-max-attributes |
| HTML Standard # attr-meter-max |
| HTML Standard # attr-progress-max |

Browser compatibility
---------------------

### html.elements.input.max

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.meter.max

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.progress.max

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `step`
* `min`
* other meter attributes: `low`, `high`, `optimum`
* Constraint validation
* Form validation
* `validityState.rangeOverflow`
* `:out-of-range`
* `<input>`
* date, month, week, time, datetime-local, number and range types, and the `<meter>`


HTML attribute: size - HTML: HyperText Markup Language

HTML attribute: size
====================

The **`size`** attribute defines the width of the `<input>` and the height of the `<select>` element. For the `input`, if the `type` attribute is text or password then it's the number of characters. This must be an integer value of 0 or higher. If no `size` is specified, or an invalid value is specified, the input has no size declared, and the form control will be the default width based on the user agent. If CSS targets the element with properties impacting the width, CSS takes precedence.

The `size` attribute has no impact on constraint validation.

Try it
------

Examples
--------

By adding `size` on some input types, the width of the input can be controlled. Adding size on a select changes the height, defining how many options are visible in the closed state.

```html
<label for="fruit">Enter a fruit</label>
<input type="text" size="15" id="fruit" />
<label for="vegetable">Enter a vegetable</label>
<input type="text" id="vegetable" />

<select name="fruits" size="5">
  <option>banana</option>
  <option>cherry</option>
  <option>strawberry</option>
  <option>durian</option>
  <option>blueberry</option>
</select>

<select name="vegetables" size="5">
  <option>carrot</option>
  <option>cucumber</option>
  <option>cauliflower</option>
  <option>celery</option>
  <option>collard greens</option>
</select>
```

Specifications
--------------

#### No specification found

No specification data found for `html.elements.attribute.size`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `maxlength`
* `minlength`
* `pattern`


HTML attribute: multiple - HTML: HyperText Markup Language

HTML attribute: multiple
========================

The Boolean **`multiple`** attribute, if set, means the form control accepts one or more values. Valid for the email and file input types and the `<select>`, the manner by which the user opts for multiple values depends on the form control.

Try it
------

Overview
--------

Depending on the type, the form control may have a different appearance if the `multiple` attribute is set. For the file input type, the native messaging the browser provides differs. In Firefox, the file input reads "No files selected" when the attribute is present and "No file selected" when it is not. Most browsers display a scrolling list box for a `<select>` control with the `multiple` attribute set and a single line dropdown when the attribute is omitted. The email input displays the same whether or not the `multiple` attribute is included, but will match the `:invalid` pseudo-class if more than one comma-separated email address is included if the attribute is not present.

When `multiple` is set on the email input type, the user can include zero (if not also `required`), one or more comma-separated email addresses.

```html
<input type="email" multiple name="emails" id="emails" />
```

If and only if the `multiple` attribute is specified, the value can be a list of properly-formed comma-separated email addresses. Any trailing and leading whitespace is removed from each address in the list.

When `multiple` is set on the file input type, the user can select one or more files. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down `Shift` or `Control`, and then clicking).

```html
<input type="file" multiple name="uploads" id="uploads" />
```

When the attribute is omitted, the user can only select a single file per `<input>`.

The `multiple` attribute on the `<select>` element represents a control for selecting zero or more options from the list of options. Otherwise, the `<select>` element represents a control for selecting a single `<option>` from the list of options.

```html
<select multiple name="dwarfs" id="dwarfs">
  <option>Grumpy</option>
  <option>Happy</option>
  <option>Sleepy</option>
  <option>Bashful</option>
  <option>Sneezy</option>
  <option>Dopey</option>
  <option>Doc</option>
</select>
```

When `multiple` is specified, most browsers will show a scrolling list box instead of a single line dropdown.

Accessibility concerns
----------------------

Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the `multiple` attribute, inform the user that multiple values are allowed and provide directions on how to provide multiple values, such as "separate email addresses with a comma."

Setting `size="1"` on a multiple select can make it appear as a single select in some browsers, but then it doesn't expand on focus, harming usability. Don't do that. If you do change the appearance of a select, and even if you don't, make sure to inform the user that more than one option can be selected by another method.

Examples
--------

### email input

```html
<label for="emails">Who do you want to email?</label>
<input
 type="email"
 multiple
 name="emails"
 id="emails"
 list="dwarf-emails"
 required
 size="64" />

<datalist id="dwarf-emails">
  <option value="grumpy@woodworkers.com">Grumpy</option>
  <option value="happy@woodworkers.com">Happy</option>
  <option value="sleepy@woodworkers.com">Sleepy</option>
  <option value="bashful@woodworkers.com">Bashful</option>
  <option value="sneezy@woodworkers.com">Sneezy</option>
  <option value="dopey@woodworkers.com">Dopey</option>
  <option value="doc@woodworkers.com">Doc</option>
</datalist>
```

```
input:invalid {
  border: red solid 3px;
}
```

If and only if the `multiple` attribute is specified, the value can be a list of properly-formed comma-separated email addresses. Any trailing and leading whitespace is removed from each address in the list. If the `required` attribute is present, at least one email address is required.

Some browsers support the appearance of the `list` of options from the associated `<datalist>` for subsequent email addresses when `multiple` is present. Others do not.

### file input

When `multiple` is set on the file input type, the user can select one or more files:

```html
<form method="post" enctype="multipart/form-data">
  <p>
    <label for="uploads"> Choose the images you want to upload: </label>
    <input
 type="file"
 id="uploads"
 name="uploads"
 accept=".jpg, .jpeg, .png, .svg, .gif"
 multiple />
  </p>
  <p>
    <label for="text">Pick a text file to upload: </label>
    <input type="file" id="text" name="text" accept=".txt" />
  </p>
  <p>
    <input type="submit" value="Submit" />
  </p>
</form>
```

Note the difference in appearance between the example with `multiple` set and the other `file` input without.

When the form is submitted, had we used `method="get"` each selected file's name would have been added to URL parameters as`?uploads=img1.jpg&uploads=img2.svg`. However, since we are submitting multipart form data, we much use post. See the `<form>` element and sending form data for more information.

### select

The `multiple` attribute on the `<select>` element represents a control for selecting zero or more options from the list of options. Otherwise, the `<select>` element represents a control for selecting a single `<option>` from the list of options. The control generally has a different appearance based on the presence of the multiple attribute, with most browsers displaying a scrolling list box instead of a single line dropdown when the attribute is present.

```html
<form method="get" action="#">
  <p>
    <label for="dwarfs">Select the dwarf woodsman you like:</label>
    <select multiple name="dwarfs" id="dwarfs">
      <option>grumpy@woodworkers.com</option>
      <option>happy@woodworkers.com</option>
      <option>sleepy@woodworkers.com</option>
      <option>bashful@woodworkers.com</option>
      <option>sneezy@woodworkers.com</option>
      <option>dopey@woodworkers.com</option>
      <option>doc@woodworkers.com</option>
    </select>
  </p>
  <p>
    <label for="favoriteOnly">Select your favorite:</label>
    <select name="favoriteOnly" id="favoriteOnly">
      <option>grumpy@woodworkers.com</option>
      <option>happy@woodworkers.com</option>
      <option>sleepy@woodworkers.com</option>
      <option>bashful@woodworkers.com</option>
      <option>sneezy@woodworkers.com</option>
      <option>dopey@woodworkers.com</option>
      <option>doc@woodworkers.com</option>
    </select>
  </p>
  <p>
    <input type="submit" value="Submit" />
  </p>
</form>
```

Note the difference in appearance between the two form controls.

```css
/\* uncomment this CSS to make the multiple the same height as the single \*/

/\*
select[multiple] {
 height: 1.5em;
 vertical-align: top;
}
select[multiple]:focus,
select[multiple]:active {
 height: auto;
}
\*/
```

There are a few ways to select multiple options in a `<select>` element with a `multiple` attribute. Depending on the operating system, mouse users can hold the `Ctrl`, `Command`, or `Shift` keys and then click multiple options to select/deselect them. Keyboard users can select multiple contiguous items by focusing on the `<select>` element, selecting an item at the top or bottom of the range they want to select using the `Up` and `Down` cursor keys to go up and down the options. The selection of non-contiguous is not as well-supported: items should be able to be selected and deselected by pressing `Space`, but support varies between browsers.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # attr-input-multiple |

See also
--------

* `<input>`
* `<select>`
* Allowing multiple email addresses


HTML attribute: minlength - HTML: HyperText Markup Language

HTML attribute: minlength
=========================

The **`minlength`** attribute defines the minimum string length that the user can enter into an `<input>` or `<textarea>`. The attribute must have an integer value of 0 or higher.

The length is measured in UTF-16 code units, which (for most scripts) is equivalent to the number of characters. If no `minlength` is specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria.

The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with `validityState.tooShort` returning `true`. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length.

Try it
------

Examples
--------

By adding `minlength="5"`, the value must either be empty or five characters or longer to be valid.

```html
<label for="fruit">Enter a fruit name that is at least 5 letters long</label>
<input type="text" minlength="5" id="fruit" />
```

We can use pseudoclasses to style the element based on whether the value is valid. The value will be valid as long as it is either null (empty) or five or more characters long. *Lime* is invalid, *lemon is valid*.

```css
input {
  border: 2px solid currentcolor;
}
input:invalid {
  border: 2px dashed red;
}
input:invalid:focus {
  background-image: linear-gradient(pink, lightgreen);
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-maxlength-and-minlength-attributes |

Browser compatibility
---------------------

### html.elements.input.minlength

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.textarea.minlength

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `maxlength`
* `size`
* `pattern`
* Constraint validation
* Form validation
* `<input>`