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/article/index.md
--- title: "<article>: The Article Contents element" slug: Web/HTML/Element/article page-type: html-element browser-compat: html.elements.article --- {{HTMLSidebar}} The **`<article>`** [HTML](/en-US/docs/Web/HTML) element represents a self-contained composition in a document, page, application, or site, which is intended to be independently distributable or reusable (e.g., in syndication). Examples include: a forum post, a magazine or newspaper article, or a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content. {{EmbedInteractiveExample("pages/tabbed/article.html", "tabbed-standard")}} A given document can have multiple articles in it; for example, on a blog that shows the text of each article one after another as the reader scrolls, each post would be contained in an `<article>` element, possibly with one or more `<section>`s within. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Each `<article>` should be identified, typically by including a heading ([`<h1>` - `<h6>`](/en-US/docs/Web/HTML/Element/Heading_Elements) element) as a child of the `<article>` element. - When an `<article>` element is nested, the inner element represents an article related to the outer element. For example, the comments of a blog post can be `<article>` elements nested in the `<article>` representing the blog post. - Author information of an `<article>` element can be provided through the {{HTMLElement("address")}} element, but it doesn't apply to nested `<article>` elements. - The publication date and time of an `<article>` element can be described using the [`datetime`](/en-US/docs/Web/HTML/Element/time#datetime) attribute of a {{HTMLElement("time")}} element. ## Examples ```html <article class="film_review"> <h2>Jurassic Park</h2> <section class="main_review"> <h3>Review</h3> <p>Dinos were great!</p> </section> <section class="user_reviews"> <h3>User reviews</h3> <article class="user_review"> <h4>Too scary!</h4> <p>Way too scary for me.</p> <footer> <p> Posted on <time datetime="2015-05-16 19:00">May 16</time> by Lisa. </p> </footer> </article> <article class="user_review"> <h4>Love the dinos!</h4> <p>I agree, dinos are my favorite.</p> <footer> <p> Posted on <time datetime="2015-05-17 19:00">May 17</time> by Tom. </p> </footer> </article> </section> <footer> <p> Posted on <time datetime="2015-05-15 19:00">May 15</time> by Staff. </p> </footer> </article> ``` ### Result {{EmbedLiveSample('Examples','','570')}} ## 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#sectioning_content" >sectioning content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content" >palpable content</a > </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>{{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#flow_content" >flow content</a >. Note that an <code>&#x3C;article></code> element must not be a descendant of an {{HTMLElement("address")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Article_Role" >article</a ></code > </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/feed_role"><code>feed</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/main_role"><code>main</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/region_role"><code>region</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other section-related elements: {{HTMLElement("body")}}, {{HTMLElement("nav")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("address")}} - [Using HTML sections and outlines](/en-US/docs/Web/HTML/Element/Heading_Elements)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/iframe/index.md
--- title: "<iframe>: The Inline Frame element" slug: Web/HTML/Element/iframe page-type: html-element browser-compat: html.elements.iframe --- {{HTMLSidebar}} The **`<iframe>`** [HTML](/en-US/docs/Web/HTML) element represents a nested {{Glossary("browsing context")}}, embedding another HTML page into the current one. {{EmbedInteractiveExample("pages/tabbed/iframe.html", "tabbed-standard")}} Each embedded browsing context has its own [document](/en-US/docs/Web/API/Document) and allows URL navigations. The navigations of each embedded browsing context are linearized into the [session history](/en-US/docs/Web/API/History) of the _topmost_ browsing context. The browsing context that embeds the others is called the _parent browsing context_. The _topmost_ browsing context — the one with no parent — is usually the browser window, represented by the {{domxref("Window")}} object. > **Warning:** Because each browsing context is a complete document environment, every `<iframe>` in a page requires increased memory and other computing resources. While theoretically you can use as many `<iframe>`s as you like, check for performance problems. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `allow` - : Specifies a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) for the `<iframe>`. The policy defines what features are available to the `<iframe>` (for example, access to the microphone, camera, battery, web-share, etc.) based on the origin of the request. See [iframes](/en-US/docs/Web/HTTP/Headers/Permissions-Policy#iframes) in the `Permissions-Policy` topic for examples. > **Note:** A Permissions Policy specified by the `allow` attribute implements a further restriction on top of the policy specified in the {{httpheader("Permissions-Policy")}} header. It doesn't replace it. - `allowfullscreen` - : Set to `true` if the `<iframe>` can activate fullscreen mode by calling the {{domxref("Element.requestFullscreen", "requestFullscreen()")}} method. > **Note:** This attribute is considered a legacy attribute and redefined as `allow="fullscreen"`. - `allowpaymentrequest` {{deprecated_inline}} {{non-standard_inline}} - : Set to `true` if a cross-origin `<iframe>` should be allowed to invoke the [Payment Request API](/en-US/docs/Web/API/Payment_Request_API). > **Note:** This attribute is considered a legacy attribute and redefined as `allow="payment"`. - `credentialless` {{Experimental_Inline}} - : Set to `true` to make the `<iframe>` credentialless, meaning that its content will be loaded in a new, ephemeral context. It doesn't have access to the network, cookies, and storage data associated with its origin. It uses a new context local to the top-level document lifetime. In return, the {{httpheader("Cross-Origin-Embedder-Policy")}} (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not. See [IFrame credentialless](/en-US/docs/Web/Security/IFrame_credentialless) for more details. - `csp` {{experimental_inline}} - : A [Content Security Policy](/en-US/docs/Web/HTTP/CSP) enforced for the embedded resource. See {{domxref("HTMLIFrameElement.csp")}} for details. - `height` - : The height of the frame in CSS pixels. Default is `150`. - `loading` - : Indicates when the browser should load the iframe: - `eager` - : Load the iframe immediately on page load (this is the default value). - `lazy` - : Defer loading of the iframe until it reaches a calculated distance from the {{glossary("visual viewport")}}, as defined by the browser. The intent is to avoid using the network and storage bandwidth required to fetch the frame until the browser is reasonably certain that it will be needed. This improves the performance and cost in most typical use cases, in particular by reducing initial page load times. > **Note:** Loading is only deferred when JavaScript is enabled. > This is an anti-tracking measure. - `name` - : A targetable name for the embedded browsing context. This can be used in the `target` attribute of the {{HTMLElement("a")}}, {{HTMLElement("form")}}, or {{HTMLElement("base")}} elements; the `formtarget` attribute of the {{HTMLElement("input")}} or {{HTMLElement("button")}} elements; or the `windowName` parameter in the {{domxref("Window.open()","window.open()")}} method. - `referrerpolicy` - : Indicates which [referrer](/en-US/docs/Web/API/Document/referrer) to send when fetching the frame's 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. - `sandbox` - : Controls the restrictions applied to the content embedded in the `<iframe>`. The value of the attribute can either be empty to apply all restrictions, or space-separated tokens to lift particular restrictions: - `allow-downloads` - : Allows downloading files through an {{HTMLElement("a")}} or {{HTMLElement("area")}} element with the [download](/en-US/docs/Web/HTML/Element/a#download) attribute, as well as through the navigation that leads to a download of a file. This works regardless of whether the user clicked on the link, or JS code initiated it without user interaction. - `allow-downloads-without-user-activation` {{experimental_inline}} - : Allows for downloads to occur without a gesture from the user. - `allow-forms` - : Allows the page to submit forms. If this keyword is not used, form will be displayed as normal, but submitting it will not trigger input validation, sending data to a web server or closing a dialog. - `allow-modals` - : Allows the page to open modal windows by {{domxref("Window.alert()")}}, {{domxref("Window.confirm()")}}, {{domxref("Window.print()")}} and {{domxref("Window.prompt()")}}, while opening a {{HTMLElement("dialog")}} is allowed regardless of this keyword. It also allows the page to receive {{domxref("BeforeUnloadEvent")}} event. - `allow-orientation-lock` - : Lets the resource [lock the screen orientation](/en-US/docs/Web/API/Screen/lockOrientation). - `allow-pointer-lock` - : Allows the page to use the [Pointer Lock API](/en-US/docs/Web/API/Pointer_Lock_API). - `allow-popups` - : Allows popups (like from {{domxref("Window.open()")}}, `target="_blank"`, {{domxref("Window.showModalDialog()")}}). If this keyword is not used, that functionality will silently fail. - `allow-popups-to-escape-sandbox` - : Allows a sandboxed document to open a new browsing context without forcing the sandboxing flags upon it. This will allow, for example, a third-party advertisement to be safely sandboxed without forcing the same restrictions upon the page the ad links to. If this flag is not included, a redirected page, popup window, or new tab will be subject to the same sandbox restrictions as the originating `<iframe>`. - `allow-presentation` - : Allows embedders to have control over whether an iframe can start a [presentation session](/en-US/docs/Web/API/PresentationRequest). - `allow-same-origin` - : If this token is not used, the resource is treated as being from a special origin that always fails the {{Glossary("same-origin policy")}} (potentially preventing access to [data storage/cookies](/en-US/docs/Web/Security/Same-origin_policy#cross-origin_data_storage_access) and some JavaScript APIs). - `allow-scripts` - : Allows the page to run scripts (but not create pop-up windows). If this keyword is not used, this operation is not allowed. - `allow-storage-access-by-user-activation` {{experimental_inline}} - : Allows a document loaded in the `<iframe>` to use the {{domxref("Storage Access API", "Storage Access API", "", "nocode")}} to request access to unpartitioned cookies. - `allow-top-navigation` - : Lets the resource navigate the top-level browsing context (the one named `_top`). - `allow-top-navigation-by-user-activation` - : Lets the resource navigate the top-level browsing context, but only if initiated by a user gesture. - `allow-top-navigation-to-custom-protocols` - : Allows navigations to non-`http` protocols built into browser or [registered by a website](/en-US/docs/Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers). This feature is also activated by `allow-popups` or `allow-top-navigation` keyword. > **Note:** > > - When the embedded document has the same origin as the embedding page, it is **strongly discouraged** to use both `allow-scripts` and `allow-same-origin`, as that lets the embedded document remove the `sandbox` attribute — making it no more secure than not using the `sandbox` attribute at all. > - Sandboxing is useless if the attacker can display content outside a sandboxed `iframe` — such as if the viewer opens the frame in a new tab. Such content should be also served from a _separate origin_ to limit potential damage. > **Note:** When redirecting the user, opening a popup window, or opening a new tab from an embedded page within an `<iframe>` with the `sandbox` attribute, the new browsing context is subject to the same `sandbox` restrictions. This can create issues — for example, if a page embedded within an `<iframe>` without a `sandbox="allow-forms"` or `sandbox="allow-popups-to-escape-sandbox"` attribute set on it opens a new site in a separate tab, form submission in that new browsing context will silently fail. - `src` - : The URL of the page to embed. Use a value of `about:blank` to embed an empty page that conforms to the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy#inherited_origins). Also note that programmatically removing an `<iframe>`'s src attribute (e.g. via {{domxref("Element.removeAttribute()")}}) causes `about:blank` to be loaded in the frame in Firefox (from version 65), Chromium-based browsers, and Safari/iOS. - `srcdoc` - : Inline HTML to embed, overriding the `src` attribute. If a browser does not support the `srcdoc` attribute, it will fall back to the URL in the `src` attribute. - `width` - : The width of the frame in CSS pixels. Default is `300`. ### Deprecated attributes These attributes are deprecated and may no longer be supported by all user agents. You should not use them in new content, and try to remove them from existing content. - `align` {{deprecated_inline}} - : The alignment of this element with respect to the surrounding context. - `frameborder` {{deprecated_inline}} - : The value `1` (the default) draws a border around this frame. The value `0` removes the border around this frame, but you should instead use the CSS property {{cssxref("border")}} to control `<iframe>` borders. - `longdesc` {{deprecated_inline}} - : A URL of a long description of the frame's content. Due to widespread misuse, this is not helpful for non-visual browsers. - `marginheight` {{deprecated_inline}} - : The amount of space in pixels between the frame's content and its top and bottom borders. - `marginwidth` {{deprecated_inline}} - : The amount of space in pixels between the frame's content and its left and right borders. - `scrolling` {{deprecated_inline}} - : Indicates when the browser should provide a scrollbar for the frame: - `auto` - : Only when the frame's content is larger than its dimensions. - `yes` - : Always show a scrollbar. - `no` - : Never show a scrollbar. ## Scripting Inline frames, like {{HTMLElement("frame")}} elements, are included in the {{domxref("window.frames")}} pseudo-array. With the DOM {{domxref("HTMLIFrameElement")}} object, scripts can access the {{domxref("window")}} object of the framed resource via the {{domxref("HTMLIFrameElement.contentWindow", "contentWindow")}} property. The {{domxref("HTMLIFrameElement.contentDocument", "contentDocument")}} property refers to the `document` inside the `<iframe>`, same as `contentWindow.document`. From the inside of a frame, a script can get a reference to its parent window with {{domxref("window.parent")}}. Script access to a frame's content is subject to the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy). Scripts cannot access most properties in other `window` objects if the script was loaded from a different origin, including scripts inside a frame accessing the frame's parent. Cross-origin communication can be achieved using {{domxref("Window.postMessage()")}}. ## Positioning and scaling As a [replaced element](/en-US/docs/Web/CSS/Replaced_element), the position, alignment, and scaling of the embedded document within the `<iframe>` element's box, can be adjusted with the {{cssxref("object-position")}} and {{cssxref("object-fit")}} properties. ## `error` and `load` event behavior The `error` and `load` events fired on `<iframe>`s could be used to probe the URL space of the local network's HTTP servers. Therefore, as a security precaution user agents do not fire the [error](/en-US/docs/Web/API/HTMLElement/error_event) event on `<iframe>`s, and the [load](/en-US/docs/Web/API/HTMLElement/load_event) event is always triggered even if the `<iframe>` content fails to load. ## Examples ### A simple \<iframe> This example embeds the page at <https://example.org> in an iframe. #### HTML ```html <iframe src="https://example.org" title="iframe Example 1" width="400" height="300"> </iframe> ``` #### Result {{ EmbedLiveSample('A_simple_iframe', 640,400)}} ## Accessibility concerns People navigating with assistive technology such as a screen reader can use the [`title` attribute](/en-US/docs/Web/HTML/Global_attributes/title) on an `<iframe>` to label its content. The title's value should concisely describe the embedded content: ```html <iframe title="Wikipedia page for Avocados" src="https://en.wikipedia.org/wiki/Avocado"></iframe> ``` Without this title, they have to navigate into the `<iframe>` to determine what its embedded content is. This context shift can be confusing and time-consuming, especially for pages with multiple `<iframe>`s and/or if embeds contain interactive content like video or audio. ## 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 >, embedded content, interactive content, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td>None.</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 embedded content.</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>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLIFrameElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [CSP: frame-ancestors](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors) - [Privacy, permissions, and information security](/en-US/docs/Web/Privacy)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/frame/index.md
--- title: <frame> slug: Web/HTML/Element/frame page-type: html-element status: - deprecated browser-compat: html.elements.frame --- {{HTMLSidebar}}{{Deprecated_Header}} The **`<frame>`** [HTML](/en-US/docs/Web/HTML) element defines a particular area in which another HTML document can be displayed. A frame should be used within a {{HTMLElement("frameset")}}. Using the `<frame>` element is not encouraged because of certain disadvantages such as performance problems and lack of accessibility for users with screen readers. Instead of the `<frame>` element, {{HTMLElement("iframe")}} may be preferred. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `src` {{Deprecated_Inline}} - : This attribute specifies the document that will be displayed by the frame. - `name` {{Deprecated_Inline}} - : This attribute is used for labeling frames. Without labeling, every link will open in the frame that it's in – the closest parent frame. See the [`target`](/en-US/docs/Web/HTML/Element/a#target) attribute for more information. - `noresize` {{Deprecated_Inline}} - : This attribute prevents resizing of frames by users. - `scrolling` {{Deprecated_Inline}} - : This attribute defines the existence of a scrollbar. If this attribute is not used, the browser adds a scrollbar when necessary. There are two choices: "yes" for forcing a scrollbar even when it is not necessary and "no" for forcing no scrollbar even when it _is_ necessary. - `marginheight` {{Deprecated_Inline}} - : This attribute defines the height of the margin between frames. - `marginwidth` {{Deprecated_Inline}} - : This attribute defines the width of the margin between frames. - `frameborder` {{Deprecated_Inline}} - : This attribute allows you to specify a frame's border. ## Example ### A frameset document A frameset document has a {{HTMLElement("frameset")}} element instead of a {{HTMLElement("body")}} element. The `<frame>` elements are placed within the `<frameset>`. ```html <!doctype html> <html lang="en-US"> <head> <!-- Document metadata goes here --> </head> <frameset cols="400, 500"> <frame src="https://developer.mozilla.org/en/HTML/Element/iframe" /> <frame src="https://developer.mozilla.org/en/HTML/Element/frame" /> </frameset> </html> ``` If you want to embed another HTML page into the {{HTMLElement("body")}} of a document, use an {{HTMLElement("iframe")}} element. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("frameset")}} - {{HTMLElement("iframe")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/input/index.md
--- title: "<input>: The Input (Form Input) element" slug: Web/HTML/Element/input page-type: html-element browser-compat: html.elements.input --- {{HTMLSidebar}} The **`<input>`** [HTML](/en-US/docs/Web/HTML) element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and {{Glossary("user agent")}}. The `<input>` element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes. {{EmbedInteractiveExample("pages/tabbed/input-text.html", "tabbed-shorter")}} ## \<input> types How an `<input>` works varies considerably depending on the value of its [`type`](#type) attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is `text`. The available types are as follows: <table class="no-markdown"> <colgroup> <col /> <col style="width: 50%" /> <col /> </colgroup> <thead> <tr> <th>Type</th> <th>Description</th> <th>Basic Examples</th> </tr> </thead> <tbody> <tr> <td>{{HTMLElement("input/button", "button")}}</td> <td> A push button with no default behavior displaying the value of the <a href="#value"><code>value</code></a> attribute, empty by default. </td> <td id="examplebutton"> <pre class="brush: html hidden"> &#x3C;input type="button" name="button" value="Button" /></pre> {{EmbedLiveSample("examplebutton",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/checkbox", "checkbox")}}</td> <td>A check box allowing single values to be selected/deselected.</td> <td id="examplecheckbox"> <pre class="brush: html hidden"> &#x3C;input type="checkbox" name="checkbox"/></pre> {{EmbedLiveSample("examplecheckbox",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/color", "color")}}</td> <td> A control for specifying a color; opening a color picker when active in supporting browsers. </td> <td id="examplecolor"> <pre class="brush: html hidden"> &#x3C;input type="color" name="color"/></pre> {{EmbedLiveSample("examplecolor",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/date", "date")}}</td> <td> A control for entering a date (year, month, and day, with no time). Opens a date picker or numeric wheels for year, month, day when active in supporting browsers. </td> <td id="exampledate"> <pre class="brush: html hidden"> &#x3C;input type="date" name="date"/></pre> {{EmbedLiveSample("exampledate",200,55)}} </td> </tr> <tr> <td> {{HTMLElement("input/datetime-local", "datetime-local")}} </td> <td> A control for entering a date and time, with no time zone. Opens a date picker or numeric wheels for date- and time-components when active in supporting browsers. </td> <td id="exampledtl"> <pre class="brush: html hidden"> &#x3C;input type="datetime-local" name="datetime-local"/></pre> {{EmbedLiveSample("exampledtl",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/email", "email")}}</td> <td> A field for editing an email address. Looks like a <code>text</code> input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards. </td> <td id="exampleemail"> <pre class="brush: html hidden"> &#x3C;input type="email" name="email"/></pre> {{EmbedLiveSample("exampleemail",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/file", "file")}}</td> <td> A control that lets the user select a file. Use the <a href="#accept"><code>accept</code></a> attribute to define the types of files that the control can select. </td> <td id="examplefile"> <pre class="brush: html hidden"> &#x3C;input type="file" accept="image/*, text/*" name="file"/></pre> {{EmbedLiveSample("examplefile",'100%',55)}} </td> </tr> <tr> <td>{{HTMLElement("input/hidden", "hidden")}}</td> <td> A control that is not displayed but whose value is submitted to the server. There is an example in the next column, but it's hidden! </td> <td id="examplehidden"> <pre class="brush: html hidden"> &#x3C;input id="userId" name="userId" type="hidden" value="abc123"></pre > {{EmbedLiveSample("examplehidden",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/image", "image")}}</td> <td> A graphical <code>submit</code> button. Displays an image defined by the <code>src</code> attribute. The <a href="#alt"><code>alt</code></a> attribute displays if the image <a href="#src"><code>src</code></a> is missing. </td> <td id="exampleimage"> <pre class="brush: html hidden"> &#x3C;input type="image" name="image" src="" alt="image input"/></pre> {{EmbedLiveSample("exampleimage",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/month", "month")}}</td> <td>A control for entering a month and year, with no time zone.</td> <td id="examplemonth"> <pre class="brush: html hidden"> &#x3C;input type="month" name="month"/></pre> {{EmbedLiveSample("examplemonth",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/number", "number")}}</td> <td> A control for entering a number. Displays a spinner and adds default validation. Displays a numeric keypad in some devices with dynamic keypads. </td> <td id="examplenumber"> <pre class="brush: html hidden"> &#x3C;input type="number" name="number"/></pre> {{EmbedLiveSample("examplenumber",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/password", "password")}}</td> <td> A single-line text field whose value is obscured. Will alert user if site is not secure. </td> <td id="examplepassword"> <pre class="brush: html hidden"> &#x3C;input type="password" name="password"/></pre> {{EmbedLiveSample("examplepassword",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/radio", "radio")}}</td> <td> A radio button, allowing a single value to be selected out of multiple choices with the same <a href="#name"><code>name</code></a> value. </td> <td id="exampleradio"> <pre class="brush: html hidden"> &#x3C;input type="radio" name="radio"/></pre > {{EmbedLiveSample("exampleradio",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/range", "range")}}</td> <td> A control for entering a number whose exact value is not important. Displays as a range widget defaulting to the middle value. Used in conjunction <a href="#min"><code>min</code></a> and <a href="#max"><code>max</code></a> to define the range of acceptable values. </td> <td id="examplerange"> <pre class="brush: html hidden"> &#x3C;input type="range" name="range" min="0" max="25"/></pre> {{EmbedLiveSample("examplerange",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/reset", "reset")}}</td> <td> A button that resets the contents of the form to default values. Not recommended. </td> <td id="examplereset"> <pre class="brush: html hidden"> &#x3C;input type="reset" name="reset"/></pre > {{EmbedLiveSample("examplereset",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/search", "search")}}</td> <td> A single-line text field for entering search strings. Line-breaks are automatically removed from the input value. May include a delete icon in supporting browsers that can be used to clear the field. Displays a search icon instead of enter key on some devices with dynamic keypads. </td> <td id="examplesearch"> <pre class="brush: html hidden"> &#x3C;input type="search" name="search"/></pre> {{EmbedLiveSample("examplesearch",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/submit", "submit")}}</td> <td>A button that submits the form.</td> <td id="examplesubmit"> <pre class="brush: html hidden"> &#x3C;input type="submit" name="submit"/></pre> {{EmbedLiveSample("examplesubmit",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/tel", "tel")}}</td> <td> A control for entering a telephone number. Displays a telephone keypad in some devices with dynamic keypads. </td> <td id="exampletel"> <pre class="brush: html hidden"> &#x3C;input type="tel" name="tel"/></pre> {{EmbedLiveSample("exampletel",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/text", "text")}}</td> <td> The default value. A single-line text field. Line-breaks are automatically removed from the input value. </td> <td id="exampletext"> <pre class="brush: html hidden"> &#x3C;input type="text" name="text"/></pre > {{EmbedLiveSample("exampletext",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/time", "time")}}</td> <td>A control for entering a time value with no time zone.</td> <td id="exampletime"> <pre class="brush: html hidden"> &#x3C;input type="time" name="time"/></pre> {{EmbedLiveSample("exampletime",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/url", "url")}}</td> <td> A field for entering a URL. Looks like a <code>text</code> input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards. </td> <td id="exampleurl"> <pre class="brush: html hidden"> &#x3C;input type="url" name="url"/></pre > {{EmbedLiveSample("exampleurl",200,55)}} </td> </tr> <tr> <td>{{HTMLElement("input/week", "week")}}</td> <td> A control for entering a date consisting of a week-year number and a week number with no time zone. </td> <td id="exampleweek"> <pre class="brush: html hidden"> &#x3C;input type="week" name="week"/></pre> {{EmbedLiveSample("exampleweek",200,55)}} </td> </tr> <tr> <th colspan="3">Obsolete values</th> </tr> <tr> <td><code>datetime</code> {{deprecated_inline}}</td> <td> A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone. </td> <td id="exampledatetime"> <pre class="brush: html hidden"> &#x3C;input type="datetime" name="datetime"/></pre> {{EmbedLiveSample("exampledatetime",200,75)}} </td> </tr> </tbody> </table> ## Attributes The `<input>` element is so powerful because of its attributes; the [`type`](#type) attribute, described with examples above, being the most important. Since every `<input>` element, regardless of type, is based on the {{domxref("HTMLInputElement")}} interface, they technically share the exact same set of attributes. However, in reality, most attributes have an effect on only a specific subset of input types. In addition, the way some attributes impact an input depends on the input type, impacting different input types in different ways. This section provides a table listing all the attributes with a brief description. This table is followed by a list describing each attribute in greater detail, along with which input types they are associated with. Those that are common to most or all input types are defined in greater detail below. Attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those types' pages. Attributes for the `<input>` element include the [global HTML attributes](/en-US/docs/Web/HTML/Global_attributes) and additionally: | Attribute | Type or Types | Description | | --------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | [`accept`](#accept) | `file` | Hint for expected file type in file upload controls | | [`alt`](#alt) | `image` | alt attribute for the image type. Required for accessibility | | [`autocapitalize`](#autocapitalize) | all except `url`, `email`, and `password` | Controls automatic capitalization in inputted text. | | [`autocomplete`](#autocomplete) | all except `checkbox`, `radio`, and buttons | Hint for form autofill feature | | [`capture`](#capture) | `file` | Media capture input method in file upload controls | | [`checked`](#checked) | `checkbox`, `radio` | Whether the command or control is checked | | [`dirname`](#dirname) | `hidden`, `text`, `search`, `url`, `tel`, `email` | Name of form field to use for sending the element's directionality in form submission | | [`disabled`](#disabled) | all | Whether the form control is disabled | | [`form`](#form) | all | Associates the control with a form element | | [`formaction`](#formaction) | `image`, `submit` | URL to use for form submission | | [`formenctype`](#formenctype) | `image`, `submit` | Form data set encoding type to use for form submission | | [`formmethod`](#formmethod) | `image`, `submit` | HTTP method to use for form submission | | [`formnovalidate`](#formnovalidate) | `image`, `submit` | Bypass form control validation for form submission | | [`formtarget`](#formtarget) | `image`, `submit` | Browsing context for form submission | | [`height`](#height) | `image` | Same as height attribute for {{htmlelement('img')}}; vertical dimension | | [`list`](#list) | all except `hidden`, `password`, `checkbox`, `radio`, and buttons | Value of the id attribute of the {{htmlelement('datalist')}} of autocomplete options | | [`max`](#max) | `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range` | Maximum value | | [`maxlength`](#maxlength) | `text`, `search`, `url`, `tel`, `email`, `password` | Maximum length (number of characters) of `value` | | [`min`](#min) | `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range` | Minimum value | | [`minlength`](#minlength) | `text`, `search`, `url`, `tel`, `email`, `password` | Minimum length (number of characters) of `value` | | [`multiple`](#multiple) | `email`, `file` | Boolean. Whether to allow multiple values | | [`name`](#name) | all | Name of the form control. Submitted with the form as part of a name/value pair | | [`pattern`](#pattern) | `text`, `search`, `url`, `tel`, `email`, `password` | Pattern the `value` must match to be valid | | [`placeholder`](#placeholder) | `text`, `search`, `url`, `tel`, `email`, `password`, `number` | Text that appears in the form control when it has no value set | | [`popovertarget`](#popovertarget) | `button` | Designates an `<input type="button">` as a control for a popover element | | [`popovertargetaction`](#popovertargetaction) | `button` | Specifies the action that a popover control should perform | | [`readonly`](#readonly) | all except `hidden`, `range`, `color`, `checkbox`, `radio`, and buttons | Boolean. The value is not editable | | [`required`](#required) | all except `hidden`, `range`, `color`, and buttons | Boolean. A value is required or must be checked for the form to be submittable | | [`size`](#size) | `text`, `search`, `url`, `tel`, `email`, `password` | Size of the control | | [`src`](#src) | `image` | Same as `src` attribute for {{htmlelement('img')}}; address of image resource | | [`step`](#step) | `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range` | Incremental values that are valid | | [`type`](#type) | all | Type of form control | | [`value`](#value) | all except `image` | The initial value of the control | | [`width`](#width) | `image` | Same as `width` attribute for {{htmlelement('img')}} | A few additional non-standard attributes are listed following the descriptions of the standard attributes. ### Individual attributes - `accept` - : Valid for the `file` input type only, the `accept` attribute defines which file types are selectable in a `file` upload control. See the {{HTMLElement("input/file", "file")}} input type. - `alt` - : Valid for the `image` button only, the `alt` attribute provides alternative text for the image, displaying the value of the attribute if the image [`src`](#src) is missing or otherwise fails to load. See the {{HTMLElement("input/image", "image")}} input type. - `autocapitalize` - : Controls whether inputted text is automatically capitalized and, if so, in what manner. See the [`autocapitalize`](/en-US/docs/Web/HTML/Global_attributes/autocapitalize) global attribute page for more information. - [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) - : (**Not** a Boolean attribute!) The [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) attribute takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide. A typical implementation of autocomplete recalls previous values entered in the same input field, but more complex forms of autocomplete can exist. For instance, a browser could integrate with a device's contacts list to autocomplete `email` addresses in an email input field. See [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete#values) for permitted values. The `autocomplete` attribute is valid on `hidden`, `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range`, `color`, and `password`. This attribute has no effect on input types that do not return numeric or text data, being valid for all input types except `checkbox`, `radio`, `file`, or any of the button types. See the [`autocomplete` attribute](/en-US/docs/Web/HTML/Attributes/autocomplete) for additional information, including information on password security and how `autocomplete` is slightly different for `hidden` than for other input types. - `autofocus` - : A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the {{HTMLElement("dialog")}} containing the element has been displayed). > **Note:** An element with the `autofocus` attribute may gain focus before the {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}} event is fired. No more than one element in the document may have the `autofocus` attribute. If put on more than one element, the first one with the attribute receives focus. The `autofocus` attribute cannot be used on inputs of type `hidden`, since hidden inputs cannot be focused. > **Warning:** 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. - `capture` - : Introduced in the HTML Media Capture specification and valid for the `file` input type only, the `capture` attribute defines which media—microphone, video, or camera—should be used to capture a new file for upload with `file` upload control in supporting scenarios. See the {{HTMLElement("input/file", "file")}} input type. - `checked` - : Valid for both `radio` and `checkbox` types, `checked` is a Boolean attribute. If present on a `radio` type, it indicates that the radio button is the currently selected one in the group of same-named radio buttons. If present on a `checkbox` type, it indicates that the checkbox is checked by default (when the page loads). It does _not_ indicate whether this checkbox is currently checked: if the checkbox's state is changed, this content attribute does not reflect the change. (Only the [`HTMLInputElement`'s `checked` IDL attribute](/en-US/docs/Web/API/HTMLInputElement) is updated.) > **Note:** Unlike other input controls, a checkboxes and radio buttons value are only included in the submitted data if they are currently `checked`. If they are, the name and the value(s) of the checked controls are submitted. > > For example, if a checkbox whose `name` is `fruit` has a `value` of `cherry`, and the checkbox is checked, the form data submitted will include `fruit=cherry`. If the checkbox isn't active, it isn't listed in the form data at all. The default `value` for checkboxes and radio buttons is `on`. - `dirname` - : Valid for `hidden`, `text`, `search`, `url`, `tel`, and `email` input types, the `dirname` attribute enables the submission of the directionality of the element. When included, the form control will submit with two name/value pairs: the first being the [`name`](#name) and [`value`](#value), and the second being the value of the `dirname` attribute as the name, with a value of `ltr` or `rtl` as set by the browser. ```html <form action="page.html" method="post"> <label> Fruit: <input type="text" name="fruit" dirname="fruit-dir" value="cherry" /> </label> <input type="submit" /> </form> <!-- page.html?fruit=cherry&fruit-dir=ltr --> ``` When the form above is submitted, the input cause both the `name` / `value` pair of `fruit=cherry` and the `dirname` / direction pair of `fruit-dir=ltr` to be sent. For more information, see the [`dirname` attribute](/en-US/docs/Web/HTML/Attributes/dirname). - `disabled` - : A Boolean attribute which, if present, indicates that the user should not be able to interact with the input. Disabled inputs are typically rendered with a dimmer color or using some other form of indication that the field is not available for use. Specifically, disabled inputs do not receive the {{domxref("Element/click_event", "click")}} event, and disabled inputs are not submitted with the form. > **Note:** Although not required by the specification, Firefox will by default [persist the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` across page loads. Use the [`autocomplete`](#autocomplete) attribute to control this feature. - `form` - : A string specifying the {{HTMLElement("form")}} element with which the input is associated (that is, its **form owner**). This string's value, if present, must match the [`id`](#id) of a `<form>` element in the same document. If this attribute isn't specified, the `<input>` element is associated with the nearest containing form, if any. The `form` attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document. > **Note:** An input can only be associated with one form. - `formaction` - : Valid for the `image` and `submit` input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information. - `formenctype` - : Valid for the `image` and `submit` input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information. - `formmethod` - : Valid for the `image` and `submit` input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information. - `formnovalidate` - : Valid for the `image` and `submit` input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information. - `formtarget` - : Valid for the `image` and `submit` input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information. - `height` - : Valid for the `image` input button only, the `height` is the height of the image file to display to represent the graphical submit button. See the {{HTMLElement("input/image", "image")}} input type. - `id` - : Global attribute valid for all elements, including all the input types, it defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking. The value is used as the value of the {{htmlelement('label')}}'s `for` attribute to link the label with the form control. See {{htmlelement('label')}}. - `inputmode` - : Global value valid for all elements, it provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Values include `none`, `text`, `tel`, `url`, `email`, `numeric`, `decimal`, and `search`. - `list` - : The value given to the `list` attribute should be the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The `<datalist>` provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. It is valid on `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `range`, and `color`. Per the specifications, the `list` attribute is not supported by the `hidden`, `password`, `checkbox`, `radio`, `file`, or any of the button types. Depending on the browser, the user may see a custom color palette suggested, tic marks along a range, or even an input that opens like a {{HTMLElement("select")}} but allows for non-listed values. Check out the [browser compatibility table](/en-US/docs/Web/HTML/Element/datalist#browser_compatibility) for the other input types. See the {{htmlelement('datalist')}} element. - `max` - : Valid for `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`, it defines the greatest value in the range of permitted values. If the [`value`](#value) entered into the element exceeds this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `max` attribute isn't a number, then the element has no maximum value. There is a special case: if the data type is periodic (such as for dates or times), the value of `max` may be lower than the value of `min`, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM. - `maxlength` - : Valid for `text`, `search`, `url`, `tel`, `email`, and `password`, it defines the maximum string length (measured in UTF-16 code units) that the user can enter into the field. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. By default, browsers prevent users from entering more characters than allowed by the `maxlength` attribute. See [Client-side validation](#client-side_validation) for more information. - `min` - : Valid for `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`, it defines the most negative value in the range of permitted values. If the [`value`](#value) entered into the element is less than this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `min` attribute isn't a number, then the element has no minimum value. This value must be less than or equal to the value of the `max` attribute. If the `min` attribute is present but is not specified or is invalid, no `min` value is applied. If the `min` attribute is valid and a non-empty value is less than the minimum allowed by the `min` attribute, constraint validation will prevent form submission. See [Client-side validation](#client-side_validation) for more information. There is a special case: if the data type is periodic (such as for dates or times), the value of `max` may be lower than the value of `min`, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM. - `minlength` - : Valid for `text`, `search`, `url`, `tel`, `email`, and `password`, it defines the minimum string length (measured in UTF-16 code units) that the user can enter into the entry field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the input has no minimum length. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long, preventing form submission. See [Client-side validation](#client-side_validation) for more information. - `multiple` - : The Boolean `multiple` attribute, if set, means the user can enter comma separated email addresses in the email widget or can choose more than one file with the `file` input. See the {{HTMLElement("input/email", "email")}} and {{HTMLElement("input/file", "file")}} input type. - `name` - : A string specifying a name for the input control. This name is submitted along with the control's value when the form data is submitted. Consider the `name` a required attribute (even though it's not). If an input has no `name` specified, or `name` is empty, the input's value is not submitted with the form! (Disabled controls, unchecked radio buttons, unchecked checkboxes, and reset buttons are also not sent.) There are two special cases: 1. `_charset_` : If used as the name of an `<input>` element of type {{HTMLElement("input/hidden", "hidden")}}, the input's `value` is automatically set by the {{Glossary("user agent")}} to the character encoding being used to submit the form. 2. `isindex`: For historical reasons, the name [`isindex`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-name) is not allowed. The [`name`](#name) attribute creates a unique behavior for radio buttons. Only one radio button in a same-named group of radio buttons can be checked at a time. Selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. The value of that one checked radio button is sent along with the name if the form is submitted, When tabbing into a series of same-named group of radio buttons, if one is checked, that one will receive focus. If they aren't grouped together in source order, if one of the group is checked, tabbing into the group starts when the first one in the group is encountered, skipping all those that aren't checked. In other words, if one is checked, tabbing skips the unchecked radio buttons in the group. If none are checked, the radio button group receives focus when the first button in the same name group is reached. Once one of the radio buttons in a group has focus, using the arrow keys will navigate through all the radio buttons of the same name, even if the radio buttons are not grouped together in the source order. When an input element is given a `name`, that name becomes a property of the owning form element's {{domxref("HTMLFormElement.elements")}} property. If you have an input whose `name` is set to `guest` and another whose `name` is `hat-size`, the following code can be used: ```js let form = document.querySelector("form"); let guestName = form.elements.guest; let hatSize = form.elements["hat-size"]; ``` When this code has run, `guestName` will be the {{domxref("HTMLInputElement")}} for the `guest` field, and `hatSize` the object for the `hat-size` field. > **Warning:** Avoid giving form elements a `name` that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input. - `pattern` - : Valid for `text`, `search`, `url`, `tel`, `email`, and `password`, the `pattern` attribute defines a regular expression that the input's [`value`](#value) must match in order 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 `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the `pattern` attribute is present but is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. If the pattern attribute is valid and a non-empty value does not match the pattern, constraint validation will prevent form submission. > **Note:** If using the `pattern` attribute, inform the user about the expected format by including explanatory text nearby. You can also include a [`title`](#title) attribute to explain what the requirements are to match the pattern; most browsers will display this title as a tooltip. The visible explanation is required for accessibility. The tooltip is an enhancement. See [Client-side validation](#client-side_validation) for more information. - `placeholder` - : Valid for `text`, `search`, `url`, `tel`, `email`, `password`, and `number`, the `placeholder` attribute provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that provides a hint as to the expected type of data, rather than an explanation or prompt. The text _must not_ include carriage returns or line feeds. So for example if a field is expected to capture a user's first name, and its label is "First Name", a suitable placeholder might be "e.g. Mustafa". > **Note:** The `placeholder` attribute is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [Labels](#labels) for more information. - `popovertarget` - : Turns an `<input type="button">` element into a popover control button; takes the ID of the popover element to control as its value. See the {{domxref("Popover API", "Popover API", "", "nocode")}} landing page for more details. - `popovertargetaction` - : Specifies the action to be performed on a popover element being controlled by a control `<input type="button">`. Possible values are: - `"hide"` - : The button will hide a shown popover. If you try to hide an already hidden popover, no action will be taken. - `"show"` - : The button will show a hidden popover. If you try to show an already showing popover, no action will be taken. - `"toggle"` - : The button will toggle a popover between showing and hidden. If the popover is hidden, it will be shown; if the popover is showing, it will be hidden. If `popovertargetaction` is omitted, `"toggle"` is the default action that will be performed by the control button. - `readonly` - : A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input. The `readonly` attribute is supported by the `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `password` input types. See the [HTML attribute: `readonly`](/en-US/docs/Web/HTML/Attributes/readonly) for more information. - `required` - : `required` is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The `required` attribute is supported by `text`, `search`, `url`, `tel`, `email`, `date`, `month`, `week`, `time`, `datetime-local`, `number`, `password`, `checkbox`, `radio`, and `file` inputs. See [Client-side validation](#client-side_validation) and the [HTML attribute: `required`](/en-US/docs/Web/HTML/Attributes/required) for more information. - `size` - : Valid for `email`, `password`, `tel`, `url`, and `text`, the `size` attribute specifies how much of the input is shown. Basically creates same result as setting CSS [`width`](/en-US/docs/Web/CSS/width) property with a few specialities. The actual unit of the value depends on the input type. For `password` and `text`, it is a number of characters (or `em` units) with a default value of `20`, and for others, it is pixels (or `px` units). CSS `width` takes precedence over the `size` attribute. - `src` - : Valid for the `image` input button only, the `src` is string specifying the URL of the image file to display to represent the graphical submit button. See the {{HTMLElement("input/image", "image")}} input type. - `step` - : Valid for `date`, `month`, `week`, `time`, `datetime-local`, `number`, and `range`, the [`step`](/en-US/docs/Web/HTML/Attributes/step) attribute is a number that specifies the granularity that the value must adhere to. If not explicitly included: - `step` defaults to 1 for `number` and `range`. - Each date/time input type has a default `step` value appropriate for the type; see the individual input pages: [`date`](/en-US/docs/Web/HTML/Element/input/date#step), [`datetime-local`](/en-US/docs/Web/HTML/Element/input/datetime-local#step), [`month`](/en-US/docs/Web/HTML/Element/input/month#step), [`time`](/en-US/docs/Web/HTML/Element/input/time#step), and [`week`](/en-US/docs/Web/HTML/Element/input/week#step). 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`](#min) and [`max`](#max)). 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`](#min) value and increments of the step value, up to the [`max`](#max) value, if specified. For example, if you have `<input type="number" min="10" step="2">`, then any even integer, `10` or greater, is valid. If omitted, `<input type="number">`, any integer is valid, but floats (like `4.2`) are not valid, because `step` defaults to `1`. For `4.2` to be valid, `step` would have had to be set to `any`, 0.1, 0.2, or any the `min` value would have had to be a number ending in `.2`, such as `<input type="number" min="-5.2">` > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the value is considered invalid in constraint validation and will match the `:invalid` pseudoclass. See [Client-side validation](#client-side_validation) for more information. - `tabindex` - : Global attribute valid for all elements, including all the input types, an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly. - `title` - : Global attribute valid for all elements, including all input types, containing 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. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the {{htmlelement('label')}} element with a `for` attribute set to the form control's [`id`](#id) attribute. See [Labels](#labels) below. - `type` - : A string specifying the type of control to render. For example, to create a checkbox, a value of `checkbox` is used. If omitted (or an unknown value is specified), the input type `text` is used, creating a plaintext input field. Permitted values are listed in [Input types](#input_types) above. - `value` - : The input control's value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using JavaScript to access the respective {{domxref("HTMLInputElement")}} object's `value` property. The `value` attribute is always optional, though should be considered mandatory for `checkbox`, `radio`, and `hidden`. - `width` - : Valid for the `image` input button only, the `width` is the width of the image file to display to represent the graphical submit button. See the {{HTMLElement("input/image", "image")}} input type. ### Non-standard attributes The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. <table class="no-markdown"> <thead> <tr> <th scope="col">Attribute</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><a href="#autocorrect"><code>autocorrect</code></a></td> <td> A string indicating whether autocorrect is <code>on</code> or <code>off</code>. <strong>Safari only.</strong> </td> </tr> <tr> <td><a href="#incremental"><code>incremental</code></a></td> <td> Whether or not to send repeated {{domxref("HTMLInputElement/search_event", "search")}} events to allow updating live search results while the user is still editing the value of the field. <strong>WebKit and Blink only (Safari, Chrome, Opera, etc.).</strong> </td> </tr> <tr> <td><code>mozactionhint</code> {{deprecated_inline}}</td> <td> <p>A string indicating the type of action that will be taken when the user presses the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. <strong>Since this attribute is deprecated, use <a href="/en-US/docs/Web/HTML/Global_attributes/enterkeyhint"><code>enterkeyhint</code></a> instead.</strong></p> </td> </tr> <tr> <td><a href="#orient"><code>orient</code></a></td> <td> Sets the orientation of the range slider. <strong>Firefox only</strong>. </td> </tr> <tr> <td><a href="#results"><code>results</code></a></td> <td> The maximum number of items that should be displayed in the drop-down list of previous search queries. <strong>Safari only.</strong> </td> </tr> <tr> <td> <a href="#webkitdirectory"><code>webkitdirectory</code></a> </td> <td> A Boolean indicating whether to only allow the user to choose a directory (or directories, if <a href="#multiple"><code>multiple</code></a> is also present) </td> </tr> </tbody> </table> - `autocorrect` {{non-standard_inline}} - : (Safari only). A string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: - `on` - : Enable automatic correction of typos, as well as processing of text substitutions if any are configured. - `off` - : Disable automatic correction and text substitutions. - `incremental` {{non-standard_inline}} - : The Boolean attribute `incremental` is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the {{Glossary("user agent")}} to process the input as a live search. As the user edits the value of the field, the user agent sends {{domxref("HTMLInputElement/search_event", "search")}} events to the {{domxref("HTMLInputElement")}} object representing the search box. This allows your code to update the search results in real time as the user edits the search. If `incremental` is not specified, the {{domxref("HTMLInputElement/search_event", "search")}} event is only sent when the user explicitly initiates a search (such as by pressing the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field). The `search` event is rate-limited so that it is not sent more frequently than an implementation-defined interval. - `orient` {{non-standard_inline}} - : Similar to the -moz-orient non-standard CSS property impacting the {{htmlelement('progress')}} and {{htmlelement('meter')}} elements, the `orient` attribute defines the orientation of the range slider. Values include `horizontal`, meaning the range is rendered horizontally, and `vertical`, where the range is rendered vertically. - `results` {{non-standard_inline}} - : The `results` attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the {{HTMLElement("input")}} element's natively-provided drop-down menu of previous search queries. The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser's default maximum number of entries is used. - `webkitdirectory` {{non-standard_inline}} - : The Boolean `webkitdirectory` attribute, if present, indicates that only directories should be available to be selected by the user in the file picker interface. See {{domxref("HTMLInputElement.webkitdirectory")}} for additional details and examples. Though originally implemented only for WebKit-based browsers, `webkitdirectory` is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative. ## Methods The following methods are provided by the {{domxref("HTMLInputElement")}} interface which represents `<input>` elements in the DOM. Also available are those methods specified by the parent interfaces, {{domxref("HTMLElement")}}, {{domxref("Element")}}, {{domxref("Node")}}, and {{domxref("EventTarget")}}. - {{domxref("HTMLInputElement.checkValidity", "checkValidity()")}} - : Returns `true` if the element's value passes validity checks; otherwise, returns `false` and fires an {{domxref("HTMLInputElement.invalid_event", "invalid")}} event at the element. - {{domxref("HTMLInputElement.reportValidity", "reportValidity()")}} - : Returns `true` if the element's value passes validity checks; otherwise, returns `false`, fires an {{domxref("HTMLInputElement.invalid_event", "invalid")}} event at the element, and (if the event isn't canceled) reports the problem to the user. - {{domxref("HTMLInputElement.select", "select()")}} - : Selects the entire content of the `<input>` element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing. - {{domxref("HTMLInputElement.setCustomValidity", "setCustomValidity()")}} - : Sets a custom message to display if the input element's value isn't valid. - {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}} - : Sets the contents of the specified range of characters in the input element to a given string. A `selectMode` parameter is available to allow controlling how the existing content is affected. - {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}} - : Selects the specified range of characters within a textual input element. Does nothing for inputs which aren't presented as text input fields. - {{domxref("HTMLInputElement.showPicker", "showPicker()")}} - : Displays the browser picker for the input element that would normally be displayed when the element is selected, but triggered from a button press or other user interaction. - {{domxref("HTMLInputElement.stepDown", "stepDown()")}} - : Decrements the value of a numeric input by one, by default, or by the specified number of units. - {{domxref("HTMLInputElement.stepUp", "stepUp()")}} - : Increments the value of a numeric input by one or by the specified number of units. ## CSS Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specifically target form controls based on their UI features, also known as UI pseudo-classes. The input element can also be targeted by type with attribute selectors. There are some properties that are especially useful as well. ### UI pseudo-classes <table class="no-markdown"> <caption> Captions super relevant to the <code>&#x3C;input></code> element: </caption> <thead> <tr> <th>Pseudo-class</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>{{Cssxref(":enabled")}}</td> <td> Any currently enabled element that can be activated (selected, clicked on, typed into, etc.) or accept focus and also has a disabled state, in which it can't be activated or accept focus. </td> </tr> <tr> <td>{{Cssxref(":disabled")}}</td> <td> Any currently disabled element that has an enabled state, meaning it otherwise could be activated (selected, clicked on, typed into, etc.) or accept focus were it not disabled. </td> </tr> <tr> <td>{{Cssxref(":read-only")}}</td> <td>Element not editable by the user</td> </tr> <tr> <td>{{Cssxref(":read-write")}}</td> <td>Element that is editable by the user.</td> </tr> <tr> <td>{{Cssxref(":placeholder-shown")}}</td> <td> Element that is currently displaying <a href="#placeholder"><code>placeholder</code> text</a>, including <code>&#x3C;input></code> and {{HTMLElement("textarea")}} elements with the <a href="#placeholder"><code>placeholder</code></a> attribute present that has, as yet, no value. </td> </tr> <tr> <td>{{Cssxref(":default")}}</td> <td> Form elements that are the default in a group of related elements. Matches {{HTMLElement("input/checkbox", "checkbox")}} and {{HTMLElement("input/radio", "radio")}} input types that were checked on page load or render. </td> </tr> <tr> <td>{{Cssxref(":checked")}}</td> <td> Matches {{HTMLElement("input/checkbox", "checkbox")}} and {{HTMLElement("input/radio", "radio")}} input types that are currently checked (and the ({{HTMLElement("option")}} in a {{HTMLElement("select")}} that is currently selected). </td> </tr> <tr> <td>{{Cssxref(":indeterminate")}}</td> <td> {{HTMLElement("input/checkbox", "checkbox")}} elements whose indeterminate property is set to true by JavaScript, {{HTMLElement("input/radio", "radio")}} elements, when all radio buttons with the same name value in the form are unchecked, and {{HTMLElement("progress")}} elements in an indeterminate state </td> </tr> <tr> <td>{{Cssxref(":valid")}}</td> <td> Form controls that can have constraint validation applied and are currently valid. </td> </tr> <tr> <td>{{Cssxref(":invalid")}}</td> <td> Form controls that have constraint validation applied and are currently not valid. Matches a form control whose value doesn't match the constraints set on it by its attributes, such as <a href="#required"><code>required</code></a>, <a href="#pattern"><code>pattern</code></a>, <a href="#step"><code>step</code></a> and <a href="#max"><code>max</code></a>. </td> </tr> <tr> <td>{{Cssxref(":in-range")}}</td> <td> A non-empty input whose current value is within the range limits specified by the <a href="#min"><code>min</code></a> and <a href="#max"><code>max</code></a> attributes and the <a href="#step"><code>step</code></a>. </td> </tr> <tr> <td>{{Cssxref(":out-of-range")}}</td> <td> A non-empty input whose current value is NOT within the range limits specified by the <a href="#min"><code>min</code></a> and <a href="#max"><code>max</code></a> attributes or does not adhere to the <a href="#step"><code>step</code></a> constraint. </td> </tr> <tr> <td>{{Cssxref(":required")}}</td> <td> <code>&#x3C;input></code>, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element that has the <a href="#required"><code>required</code></a> attribute set on it. Only matches elements that can be required. The attribute included on a non-requirable element will not make for a match. </td> </tr> <tr> <td>{{Cssxref(":optional")}}</td> <td> <code>&#x3C;input></code>, {{HTMLElement("select")}}, or {{HTMLElement("textarea")}} element that does NOT have the <a href="#required"><code>required</code></a> attribute set on it. Does not match elements that can't be required. </td> </tr> <tr> <td>{{Cssxref(":blank")}}</td> <td> <code>&#x3C;input></code> and {{HTMLElement("textarea")}} elements that currently have no value. </td> </tr> <tr> <td>{{Cssxref(":user-invalid")}}</td> <td> Similar to <code>:invalid</code>, but is activated on blur. Matches invalid input but only after the user interaction, such as by focusing on the control, leaving the control, or attempting to submit the form containing the invalid control. </td> </tr> </tbody> </table> #### Pseudo-classes example We can style a checkbox label based on whether the checkbox is checked or not. In this example, we are styling the {{cssxref('color')}} and {{cssxref('font-weight')}} of the {{htmlelement('label')}} that comes immediately after a checked input. We haven't applied any styles if the `input` is not checked. ```html hidden <input id="checkboxInput" type="checkbox" /> <label for="checkboxInput">Toggle the checkbox on and off</label> ``` ```css input:checked + label { color: red; font-weight: bold; } ``` {{EmbedLiveSample('Pseudo-classes_example', 500, 80)}} ### Attribute selectors It is possible to target different types of form controls based on their [`type`](#type) using [attribute selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors). CSS attribute selectors match elements based on either just the presence of an attribute or the value of a given attribute. ```css /* matches a password input */ input[type="password"] { } /* matches a form control whose valid values are limited to a range of values*/ input[min][max] { } /* matches a form control with a pattern attribute */ input[pattern] { } ``` ### ::placeholder By default, the appearance of placeholder text is a translucent or light gray. The {{cssxref('::placeholder')}} pseudo-element is the input's [`placeholder` text](#placeholder). It can be styled with a limited subset of CSS properties. ```css ::placeholder { color: blue; } ``` Only the subset of CSS properties that apply to the {{cssxref("::first-line")}} pseudo-element can be used in a rule using `::placeholder` in its selector. ### appearance The {{cssxref("appearance")}} property enables the displaying of (almost) any element as a platform-native style based on the operating system's theme as well as the removal of any platform-native styling with the `none` value. You could make a `<div>` look like a radio button with `div {appearance: radio;}` or a radio look like a checkbox with `[type="radio"] {appearance: checkbox;}`, but don't. Setting `appearance: none` removes platform native borders, but not functionality. ### caret-color A property specific to text entry-related elements is the CSS {{cssxref("caret-color")}} property, which lets you set the color used to draw the text input caret: #### HTML ```html <label for="textInput">Note the red caret:</label> <input id="textInput" class="custom" size="32" /> ``` #### CSS ```css input.custom { caret-color: red; font: 16px "Helvetica", "Arial", "sans-serif"; } ``` #### Result {{EmbedLiveSample('caret-color', 500, 80)}} ### object-position and object-fit In certain cases (typically involving non-textual inputs and specialized interfaces), the `<input>` element is a [replaced element](/en-US/docs/Web/CSS/Replaced_element). When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS {{cssxref("object-position")}} and {{cssxref("object-fit")}} properties ### Styling For more information about adding color to elements in HTML, see: - [Applying color to HTML elements using CSS](/en-US/docs/Web/CSS/CSS_colors/Applying_color). Also see: - [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms) - [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling) and - the [compatibility table of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls). ## Additional features ### Labels Labels are needed to associate assistive text with an `<input>`. The {{HTMLElement("label")}} element provides explanatory information about a form field that is _always_ appropriate (aside from any layout concerns you have). It's never a bad idea to use a `<label>` to explain what should be entered into an `<input>` or {{HTMLElement("textarea")}}. #### Associated labels The semantic pairing of `<input>` and `<label>` elements is useful for assistive technologies such as screen readers. By pairing them using the `<label>`'s [`for`](/en-US/docs/Web/HTML/Element/label#for) attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely. It does not suffice to have plain text adjacent to the `<input>` element. Rather, usability and accessibility requires the inclusion of either implicit or explicit {{HTMLElement("label")}}: ```html <!-- inaccessible --> <p>Enter your name: <input id="name" type="text" size="30" /></p> <!-- implicit label --> <p> <label>Enter your name: <input id="name" type="text" size="30" /></label> </p> <!-- explicit label --> <p> <label for="name">Enter your name: </label> <input id="name" type="text" size="30" /> </p> ``` The first example is inaccessible: no relationship exists between the prompt and the `<input>` element. In addition to an accessible name, the label provides a larger 'hit' area for mouse and touch screen users to click on or touch. By pairing a `<label>` with an `<input>`, clicking on either one will focus the `<input>`. If you use plain text to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions. As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your website—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels. #### Placeholders are not accessible The [`placeholder`](#placeholder) attribute lets you specify text that appears within the `<input>` element's content area itself when it is empty. The placeholder should never be required to understand your forms. It is not a label, and should not be used as a substitute, because it isn't. The placeholder is used to provide a hint as to what an inputted value should look like, not an explanation or prompt. Not only is the placeholder not accessible to screen readers, but once the user enters any text into the form control, or if the form control already has a value, the placeholder disappears. Browsers with automatic page translation features may skip over attributes when translating, meaning the `placeholder` may not get translated. > **Note:** Don't use the [`placeholder`](#placeholder) attribute if you can avoid it. If you need to label an `<input>` element, use the {{HTMLElement("label")}} element. ### Client-side validation > **Warning:** Client-side validation is useful, but it does _not_ guarantee that the server will receive valid data. If the data must be in a specific format, _always_ verify it also on the server-side, and return a [`400` HTTP response](/en-US/docs/Web/HTTP/Status/400) if the format is invalid. In addition to using CSS to style inputs based on the {{cssxref(":valid")}} or {{cssxref(":invalid")}} UI states based on the current state of each input, as noted in the [UI pseudo-classes](#ui_pseudo-classes) section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if there is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you. Some input types and other attributes place limits on what values are valid for a given input. For example, `<input type="number" min="2" max="10" step="2">` means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a `rangeUnderflow` error if the value is less than 2, `rangeOverflow` if greater than 10, `stepMismatch` if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the `step` attribute), or `typeMismatch` if the value is not a number. For the input types whose domain of possible values is periodic (that is, at the highest possible value, the values wrap back around to the beginning rather than ending), it's possible for the values of the [`max`](#max) and [`min`](#min) properties to be reversed, which indicates that the range of permitted values starts at `min`, wraps around to the lowest possible value, then continues on until `max` is reached. This is particularly useful for dates and times, such as when you want to allow the range to be from 8 PM to 8 AM: ```html <input type="time" min="20:00" max="08:00" name="overnight" /> ``` Specific attributes and their values can lead to a specific error {{domxref('ValidityState')}}: <table class="no-markdown"> <caption> Validity object errors depend on the {{htmlelement('input')}} attributes and their values: </caption> <thead> <tr> <th scope="col">Attribute</th> <th scope="col">Relevant property</th> <th scope="col">Description</th> </tr> </thead> <tbody> <tr> <td><a href="#max"><code>max</code></a></td> <td>{{domxref('validityState.rangeOverflow')}}</td> <td> Occurs when the value is greater than the maximum value as defined by the <code>max</code> attribute </td> </tr> <tr> <td><a href="#maxlength"><code>maxlength</code></a></td> <td>{{domxref('validityState.tooLong')}}</td> <td> Occurs when the number of characters is greater than the number allowed by the <code>maxlength</code> property </td> </tr> <tr> <td><a href="#min"><code>min</code></a></td> <td>{{domxref('validityState.rangeUnderflow')}}</td> <td> Occurs when the value is less than the minimum value as defined by the <code>min</code> attribute </td> </tr> <tr> <td><a href="#minlength"><code>minlength</code></a></td> <td>{{domxref('validityState.tooShort')}}</td> <td> Occurs when the number of characters is less than the number required by the <code>minlength</code> property </td> </tr> <tr> <td><a href="#pattern"><code>pattern</code></a></td> <td>{{domxref('validityState.patternMismatch')}}</td> <td> Occurs when a pattern attribute is included with a valid regular expression and the <code>value</code> does not match it. </td> </tr> <tr> <td><a href="#required"><code>required</code></a></td> <td>{{domxref('validityState.valueMissing')}}</td> <td> Occurs when the <code>required</code> attribute is present but the value is <code>null</code> or radio or checkbox is not checked. </td> </tr> <tr> <td><a href="#step"><code>step</code></a></td> <td>{{domxref('validityState.stepMismatch')}}</td> <td> The value doesn't match the step increment. Increment default is <code>1</code>, so only integers are valid on<code> type="number"</code> is step is not included. <code>step="any"</code> will never throw this error. </td> </tr> <tr> <td><a href="#type"><code>type</code></a></td> <td>{{domxref('validityState.typeMismatch')}}</td> <td> Occurs when the value is not of the correct type, for example an email does not contain an <code>@</code> or a url doesn't contain a protocol. </td> </tr> </tbody> </table> If a form control doesn't have the `required` attribute, no value, or an empty string, is not invalid. Even if the above attributes are present, with the exception of `required`, an empty string will not lead to an error. We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted. In addition to the errors described in the table above, the `validityState` interface contains the `badInput`, `valid`, and `customError` boolean readonly properties. The validity object includes: - {{domxref('validityState.valueMissing')}} - {{domxref('validityState.typeMismatch')}} - {{domxref('validityState.patternMismatch')}} - {{domxref('validityState.tooLong')}} - {{domxref('validityState.tooShort')}} - {{domxref('validityState.rangeUnderflow')}} - {{domxref('validityState.rangeOverflow')}} - {{domxref('validityState.stepMismatch')}} - {{domxref('validityState.badInput')}} - {{domxref('validityState', 'validityState.valid')}} - {{domxref('validityState', 'validityState.customError')}} For each of these Boolean properties, a value of `true` indicates that the specified reason validation may have failed is true, with the exception of the `valid` property, which is `true` if the element's value obeys all constraints. If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or `null`), the form will be prevented from being submitted. If there is no custom error message, and none of the other properties return true, `valid` will be true, and the form can be submitted. ```js function validate(input) { let validityState_object = input.validity; if (validityState_object.valueMissing) { input.setCustomValidity("A value is required"); } else if (validityState_object.rangeUnderflow) { input.setCustomValidity("Your value is too low"); } else if (validityState_object.rangeOverflow) { input.setCustomValidity("Your value is too high"); } else { input.setCustomValidity(""); } } ``` The last line, setting the custom validity message to the empty string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all the values are valid, until the message is `null`. #### Custom validation error example If you want to present a custom error message when a field fails to validate, you need to use the [Constraint Validation API](/en-US/docs/Learn/Forms/Form_validation#validating_forms_using_javascript) available on `<input>` (and related) elements. Take the following form: ```html <form> <label for="name">Enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[A-Za-z]+" /> <button>Submit</button> </form> ``` The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the `pattern`. If you wanted to instead display custom error messages, you could use JavaScript like the following: ```js const nameInput = document.querySelector("input"); nameInput.addEventListener("input", () => { nameInput.setCustomValidity(""); nameInput.checkValidity(); }); nameInput.addEventListener("invalid", () => { if (nameInput.value === "") { nameInput.setCustomValidity("Enter your username!"); } else { nameInput.setCustomValidity( "Usernames can only contain upper and lowercase letters. Try again!", ); } }); ``` The example renders like so: {{EmbedLiveSample('Custom_validation_error_example')}} In brief: - We check the valid state of the input element every time its value is changed by running the `checkValidity()` method via the `input` event handler. - If the value is invalid, an `invalid` event is raised, and the `invalid` event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an `if ()` block, and set a custom validity error message. - As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown. - If it is valid, it will submit as you'd expect. For this to happen, the custom validity has to be cancelled, by invoking `setCustomValidity()` with an empty string value. We therefore do this every time the `input` event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it currently contains a valid value on submission. > **Note:** Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the _server side_. Invalid values can still be sent by older browsers or by bad actors. > **Note:** Firefox supported a proprietary error attribute — `x-moz-errormessage` — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see [Firefox bug 1513890](https://bugzil.la/1513890)). ### Localization The allowed inputs for certain `<input>` types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00. Firefox uses the following heuristics to determine the locale to validate the user's input (at least for `type="number"`): - Try the language specified by a `lang`/`xml:lang` attribute on the element or any of its parents. - Try the language specified by any `Content-Language` HTTP header. Or, - If none specified, use the browser's locale. ### 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>, listed, submittable, resettable, form-associated element, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">phrasing content</a>. If the <a href="#type"><code>type</code></a> is not <code>hidden</code>, then labelable element, palpable content. </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 <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> <ul> <li> <code>type=button</code>: <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role">button</a></code> </li> <li> <code>type=checkbox</code>: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role">checkbox</a></code> </li> <li> <code>type=email</code> <ul> <li> with no <code>list</code> attribute: <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code> </li> <li> with <code>list</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a> </li> </ul> </li> <li> <code>type=image</code>: <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role">button</a></code> </li> <li> <code>type=number</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role"><code>spinbutton</code></a> </li> <li><code>type=radio</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role"><code>radio</code></a></li> <li><code>type=range</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role"><code>slider</code></a></li> <li> <code>type=reset</code>: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role">button</a></code> </li> <li> <code>type=search</code> <ul> <li> with no <code>list</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/searchbox_role"><code>searchbox</code></a> </li> <li> with <code>list</code> attribute:<a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a> </li> </ul> </li> <li> <code>type=submit</code>: <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role">button</a></code> </li> <li> <code>type=tel</code> <ul> <li> with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code> </li> <li> with <code>list</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a> </li> </ul> </li> <li> <code>type=text</code> <ul> <li> with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code> </li> <li> with <code>list</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a> </li> </ul> </li> <li> <code>type=url</code> <ul> <li> with no <code>list</code> attribute: <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a ></code> </li> <li> with <code>list</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a> </li> </ul> </li> <li> <code>type=color|date|datetime-local|file|hidden|month|password|time|week</code>: <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role">no corresponding role</a> </li> </ul> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <ul> <li> <code>type=button</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role"><code>checkbox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/link_role"><code>link</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role"><code>menuitem</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role"><code>menuitemcheckbox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role"><code>menuitemradio</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/option_role"><code>option</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role"><code>radio</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role"><code>switch</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role"><code>tab</code></a> </li> <li> <code>type=checkbox</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role"><code>button</code></a> when used with <code>aria-pressed</code>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role"><code>menuitemcheckbox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/option_role"><code>option</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role"><code>switch</code></a> </li> <li> <code>type=image</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/link_role"><code>link</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role"><code>menuitem</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role"><code>menuitemcheckbox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role"><code>menuitemradio</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role"><code>radio</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role"><code>switch</code></a> </li> <li> <code>type=radio</code>: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role"><code>menuitemradio</code></a> </li> <li> <code>type=text</code> with no <code>list</code> attribute: <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/searchbox_role"><code>searchbox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role"><code>spinbutton</code></a> </li> <li> <code>type=color|date|datetime-local|email|file|hidden|</code> <code>month|number|password|range|reset|search|submit|tel|url|week</code> or <code>text</code> with <code>list</code> attribute: no <code>role</code> permitted </li> </ul> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLInputElement")}}</td> </tr> </tbody> </table> ## Accessibility concerns ### Labels When including inputs, it is an accessibility requirement to add labels alongside. This is needed so those who use assistive technologies can tell what the input is for. Also, clicking or touching a label gives focus to the label's associated form control. This improves the accessibility and usability for sighted users, increases the area a user can click or touch to activate the form control. This is especially useful (and even needed) for radio buttons and checkboxes, which are tiny. For more information about labels in general see [Labels](#labels) . The following is an example of how to associate the `<label>` with an `<input>` element in the above style. You need to give the `<input>` an `id` attribute. The `<label>` then needs a `for` attribute whose value is the same as the input's `id`. ```html <label for="peas">Do you like peas?</label> <input type="checkbox" name="peas" id="peas" /> ``` ### Size Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44 [CSS pixels](https://www.w3.org/TR/WCAG21/#dfn-css-pixels) is recommended. - [Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/target-size.html) - [Target Size and 2.5.5 | Adrian Roselli](https://adrianroselli.com/2019/06/target-size-and-2-5-5.html) - [Quick test: Large touch targets - The A11Y Project](https://www.a11yproject.com/posts/large-touch-targets/) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Form constraint validation](/en-US/docs/Web/HTML/Constraint_validation) - [Your first HTML form](/en-US/docs/Learn/Forms/Your_first_form) - [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form) - [The native form widgets](/en-US/docs/Learn/Forms/Basic_native_form_controls) - [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) - [Form data validation](/en-US/docs/Learn/Forms/Form_validation) - [How to build custom form widgets](/en-US/docs/Learn/Forms/How_to_build_custom_form_controls) - [HTML forms in legacy browsers](/en-US/docs/Learn/Forms/HTML_forms_in_legacy_browsers) - [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms) - [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling) - [CSS property compatibility table](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/hidden/index.md
--- title: <input type="hidden"> slug: Web/HTML/Element/input/hidden page-type: html-element browser-compat: html.elements.input.type_hidden --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`hidden`** let web developers include data that cannot be seen or modified by users when a form is submitted. For example, the ID of the content that is currently being ordered or edited, or a unique security token. Hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content. > **Note:** The {{domxref("Element/input_event", "input")}} and {{domxref("HTMLElement/change_event", "change")}} events do not apply to this input type. Hidden inputs cannot be focused even using JavaScript (e.g. `hiddenInput.focus()`). ## Value The {{HTMLElement("input")}} element's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute holds a string that contains the hidden data you want to include when the form is submitted to the server. This specifically can't be edited or seen by the user via the user interface, although you could edit the value via browser developer tools. > **Warning:** While the value isn't displayed to the user in the page's content, it is visible—and can be edited—using any browser's developer tools or "View Source" functionality. Do not rely on `hidden` inputs as a form of security. ## Additional attributes In addition to the attributes common to all {{HTMLElement("input")}} elements, `hidden` inputs offer the following attributes. ### name This is actually one of the common attributes, but it has a special meaning available for hidden inputs. Normally, the [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute functions on hidden inputs just like on any other input. However, when the form is submitted, a hidden input whose `name` is set to `_charset_` will automatically be reported with the value set to the character encoding used to submit the form. ## Using hidden inputs As mentioned above, hidden inputs can be used anywhere that you want to include data the user can't see or edit along with the form when it's submitted to the server. Let's look at some examples that illustrate its use. ### Tracking edited content One of the most common uses for hidden inputs is to keep track of what database record needs to be updated when an edit form is submitted. A typical workflow looks like this: 1. User decides to edit some content they have control over, such as a blog post, or a product entry. They get started by pressing the edit button. 2. The content to be edited is taken from the database and loaded into an HTML form to allow the user to make changes. 3. After editing, the user submits the form, and the updated data is sent back to the server to be updated in the database. The idea here is that during step 2, the ID of the record being updated is kept in a hidden input. When the form is submitted in step 3, the ID is automatically sent back to the server with the record content. The ID lets the site's server-side component know exactly which record needs to be updated with the submitted data. You can see a full example of what this might look like in the [Examples](#examples) section below. ### Improving website security Hidden inputs are also used to store and submit security tokens or _secrets_, for the purposes of improving website security. The basic idea is that if a user is filling in a sensitive form, such as a form on their banking website to transfer some money to another account, the secret they would be provided with would prove that they are who they say they are, and that they are using the correct form to submit the transfer request. This would stop a malicious user from creating a fake form, pretending to be a bank, and emailing the form to unsuspecting users to trick them into transferring money to the wrong place. This kind of attack is called a [Cross Site Request Forgery (CSRF)](</en-US/docs/Learn/Server-side/First_steps/Website_security#cross-site_request_forgery_(csrf)>); pretty much any reputable server-side framework uses hidden secrets to prevent such attacks. > **Note:** Placing the secret in a hidden input doesn't inherently make it secure. The key's composition and encoding would do that. The value of the hidden input is that it keeps the secret associated with the data and automatically includes it when the form is sent to the server. You need to use well-designed secrets to actually secure your website. ## Validation Hidden inputs don't participate in constraint validation; they have no real value to be constrained. ## Examples Let's look at how we might implement a simple version of the edit form we described earlier (see [Tracking edited content](#tracking_edited_content)), using a hidden input to remember the ID of the record being edited. The edit form's HTML might look a bit like this: ```html <form> <div> <label for="title">Post title:</label> <input type="text" id="title" name="title" value="My excellent blog post" /> </div> <div> <label for="content">Post content:</label> <textarea id="content" name="content" cols="60" rows="5"> This is the content of my excellent blog post. I hope you enjoy it! </textarea> </div> <div> <button type="submit">Update post</button> </div> <input type="hidden" id="postId" name="postId" value="34657" /> </form> ``` Let's also add some simple CSS: ```css html { font-family: sans-serif; } form { width: 500px; } div { display: flex; margin-bottom: 10px; } label { flex: 2; line-height: 2; text-align: right; padding-right: 20px; } input, textarea { flex: 7; font-family: sans-serif; font-size: 1.1rem; padding: 5px; } textarea { height: 60px; } ``` The server would set the value of the hidden input with the ID "`postID`" to the ID of the post in its database before sending the form to the user's browser and would use that information when the form is returned to know which database record to update with modified information. No scripting is needed in the content to handle this. The output looks like this: {{ EmbedLiveSample('Examples', '100%', 200) }} > **Note:** You can also find the example on GitHub (see the [source code](https://github.com/mdn/learning-area/blob/main/html/forms/hidden-input-example/index.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/hidden-input-example/index.html)). When submitted, the form data sent to the server will look something like this: `title=My+excellent+blog+post&content=This+is+the+content+of+my+excellent+blog+post.+I+hope+you+enjoy+it!&postId=34657` Even though the hidden input cannot be seen at all, its data is still submitted. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing the value of the hidden data you want to pass back to the server. </td> </tr> <tr> <td><strong>Events</strong></td> <td>None.</td> </tr> <tr> <td><strong>Supported Common Attributes</strong></td> <td><a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a></td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td>None.</td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML forms guide](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface it's based upon
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/color/index.md
--- title: <input type="color"> slug: Web/HTML/Element/input/color page-type: html-element browser-compat: html.elements.input.type_color --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`color`** provide a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in `#rrggbb` hexadecimal format. Only simple colors (without alpha channel) are allowed though CSS colors has more formats, e.g. color names, functional notations and a hexadecimal format with an alpha channel. The element's presentation may vary substantially from one browser and/or platform to another—it might be a simple textual input that automatically validates to ensure that the color information is entered in the proper format, or a platform-standard color picker, or some kind of custom color picker window. {{EmbedInteractiveExample("pages/tabbed/input-color.html", "tabbed-standard")}} ## Value The [`value`](/en-US/docs/Web/HTML/Element/input#value) of an {{HTMLElement("input")}} element of type `color` is always a string which contains a 7-character string specifying an RGB color in hexadecimal format. While you can input the color in either upper- or lower-case, it will be stored in lower-case form. The value is never in any other form, and is never empty. > **Note:** Setting the value to anything that isn't a valid, fully-opaque, RGB color _in hexadecimal notation_ will result in the value being set to `#000000`. In particular, you can't use CSS's standardized color names, or any CSS function syntax, to set the value. This makes sense when you keep in mind that HTML and CSS are separate languages and specifications. In addition, colors with an alpha channel are not supported; specifying a color in 9-character hexadecimal notation (e.g. `#009900aa`) will also result in the color being set to `#000000`. ## Using color inputs Inputs of type `color` are simple, due to the limited number of attributes they support. ### Providing a default color You can update the simple example above to set a default value, so that the color picker is pre-filled with the default color and the color picker (if any) will also default to that color: ```html <input type="color" value="#ff0000" /> ``` {{EmbedLiveSample("Providing_a_default_color", 700, 30)}} If you don't specify a value, the default is `#000000`, which is black. The value must be in seven-character hexadecimal notation, meaning the "#" character followed by two digits each representing red, green, and blue, like this: `#rrggbb`. If you have colors that are in any other format (such as CSS color names or CSS color functions such as `rgb()` or `hsl()` ), you'll have to convert them to hexadecimal before setting the `value`. ### Tracking color changes As is the case with other {{HTMLElement("input")}} types, there are two events that can be used to detect changes to the color value: {{domxref("Element/input_event", "input")}} and {{domxref("HTMLElement/change_event", "change")}}. `input` is fired on the `<input>` element every time the color changes. The `change` event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its [`value`](/en-US/docs/Web/HTML/Element/input#value). Here's an example that watches changes over time to the color value: ```js colorPicker.addEventListener("input", updateFirst, false); colorPicker.addEventListener("change", watchColorPicker, false); function watchColorPicker(event) { document.querySelectorAll("p").forEach((p) => { p.style.color = event.target.value; }); } ``` ### Selecting the value When a browser doesn't support a color picker interface, its implementation of color inputs will be a text box that validates the contents automatically to ensure that the value is in the correct format. In this case you can use the {{domxref("HTMLInputElement.select", "select()")}} method to select the text currently in the edit field. If the browser instead uses a color picker, `select()` does nothing. You should be aware of this behavior so your code can respond appropriately in either case. ```js colorPicker.select(); ``` ## Validation A color input's value is considered to be invalid if the {{Glossary("user agent")}} is unable to convert the user's input into seven-character lower-case hexadecimal notation. If and when this is the case, the {{cssxref(":invalid")}} pseudo-class is applied to the element. ## Example Let's create an example which does a little more with the color input by tracking the {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} events to take the new color and apply it to every {{HTMLElement("p")}} element in the document. ### HTML The HTML is fairly straightforward — a couple of paragraphs of descriptive material with an {{HTMLElement("input")}} of type `color` with the ID `color-picker`, which we'll use to change the color of the paragraphs' text. ```html <p> An example demonstrating the use of the <code>&lt;input type="color"&gt;</code> control. </p> <label for="color-picker">Color:</label> <input type="color" value="#ff0000" id="color-picker" /> <p> Watch the paragraph colors change when you adjust the color picker. As you make changes in the color picker, the first paragraph's color changes, as a preview (this uses the <code>input</code> event). When you close the color picker, the <code>change</code> event fires, and we detect that to change every paragraph to the selected color. </p> ``` ### JavaScript First, there's some setup. Here we establish some variables, setting up a variable that contains the color we'll set the color picker to when we first load up, and then setting up a {{domxref("Window/load_event", "load")}} handler to do the main startup work once the page is fully loaded. ```js let colorPicker; const defaultColor = "#0000ff"; window.addEventListener("load", startup, false); ``` #### Initialization Once the page is loaded, our `load` event handler, `startup()`, is called: ```js function startup() { colorPicker = document.querySelector("#color-picker"); colorPicker.value = defaultColor; colorPicker.addEventListener("input", updateFirst, false); colorPicker.addEventListener("change", updateAll, false); colorPicker.select(); } ``` This gets a reference to the color `<input>` element in a variable called `colorPicker`, then sets the color input's value to the value in `defaultColor`. Then the color input's {{domxref("Element/input_event", "input")}} event is set up to call our `updateFirst()` function, and the {{domxref("HTMLElement/change_event", "change")}} event is set to call `updateAll()`. These are both seen below. Finally, we call {{domxref("HTMLInputElement.select", "select()")}} to select the text content of the color input if the control is implemented as a text field (this has no effect if a color picker interface is provided instead). #### Reacting to color changes We provide two functions that deal with color changes. The `updateFirst()` function is called in response to the `input` event. It changes the color of the first paragraph element in the document to match the new value of the color input. Since `input` events are fired every time an adjustment is made to the value (for example, if the brightness of the color is increased), these will happen repeatedly as the color picker is used. ```js function updateFirst(event) { const p = document.querySelector("p"); if (p) { p.style.color = event.target.value; } } ``` When the color picker is dismissed, indicating that the value will not change again (unless the user re-opens the color picker), a `change` event is sent to the element. We handle that event using the `updateAll()` function, using [`Event.target.value`](/en-US/docs/Web/HTML/Element/input#value) to obtain the final selected color: ```js function updateAll(event) { document.querySelectorAll("p").forEach((p) => { p.style.color = event.target.value; }); } ``` This sets the color of every {{HTMLElement("p")}} block so that its {{cssxref("color")}} attribute matches the current value of the color input, which is referred to using {{domxref("Event.target", "event.target")}}. ### Result The final result looks like this: {{EmbedLiveSample("Example", 700, 200)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A 7-character string specifying a {{cssxref("&lt;color&gt;")}} in lower-case hexadecimal notation </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a> and <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>list</code> and <code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/button/index.md
--- title: <input type="button"> slug: Web/HTML/Element/input/button page-type: html-element browser-compat: html.elements.input.type_button --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`button`** are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the {{domxref("Element/click_event", "click")}} event). {{EmbedInteractiveExample("pages/tabbed/input-button.html", "tabbed-shorter")}} > **Note:** While `<input>` elements of type `button` are still perfectly valid HTML, the newer {{HTMLElement("button")}} element is now the favored way to create buttons. Given that a {{HTMLElement("button")}}'s label text is inserted between the opening and closing tags, you can include HTML in the label, even images. ## Value ### Button with a value An `<input type="button">` elements' [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string that is used as the button's label. The `value` provides the {{glossary("accessible description")}} for the button. ```html <input type="button" value="Click Me" /> ``` {{EmbedLiveSample("Button_with_a_value", 650, 30)}} ### Button without a value If you don't specify a `value`, you get an empty button: ```html <input type="button" /> ``` {{EmbedLiveSample("Button_without_a_value", 650, 30)}} ## Using buttons `<input type="button">` elements have no default behavior (their cousins, `<input type="submit">` and [`<input type="reset">`](/en-US/docs/Web/HTML/Element/input/reset) are used to submit and reset forms, respectively). To make buttons do anything, you have to write JavaScript code to do the work. ### A simple button We'll begin by creating a simple button with a {{domxref("Element/click_event", "click")}} event handler that starts our machine (well, it toggles the `value` of the button and the text content of the following paragraph): ```html <form> <input type="button" value="Start machine" /> </form> <p>The machine is stopped.</p> ``` ```js const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() { if (button.value === "Start machine") { button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; } else { button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; } } ``` The script gets a reference to the {{domxref("HTMLInputElement")}} object representing the `<input>` in the DOM, saving this reference in the variable `button`. {{domxref("EventTarget.addEventListener", "addEventListener()")}} is then used to establish a function that will be run when {{domxref("Element/click_event", "click")}} events occur on the button. {{EmbedLiveSample("A_simple_button", 650, 100)}} ### Adding keyboard shortcuts to buttons Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any {{HTMLElement("input")}} for which it makes sense — you use the [`accesskey`](/en-US/docs/Web/HTML/Global_attributes/accesskey) global attribute. In this example, <kbd>s</kbd> is specified as the access key (you'll need to press <kbd>s</kbd> plus the particular modifier keys for your browser/OS combination; see [accesskey](/en-US/docs/Web/HTML/Global_attributes/accesskey) for a useful list of those). ```html <form> <input type="button" value="Start machine" accesskey="s" /> </form> <p>The machine is stopped.</p> ``` ```js hidden const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() { if (button.value === "Start machine") { button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; } else { button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; } } ``` {{EmbedLiveSample("Adding_keyboard_shortcuts_to_buttons", 650, 100)}} > **Note:** The problem with the above example of course is that the user will not know what the access key is! In a real site, you'd have to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are). ### Disabling and enabling a button To disable a button, specify the [`disabled`](/en-US/docs/Web/HTML/Attributes/disabled) global attribute on it, like so: ```html <input type="button" value="Disable me" disabled /> ``` #### Setting the disabled attribute You can enable and disable buttons at run time by setting `disabled` to `true` or `false`. In this example our button starts off enabled, but if you press it, it is disabled using `button.disabled = true`. A {{domxref("setTimeout()")}} function is then used to reset the button back to its enabled state after two seconds. ```html <input type="button" value="Enabled" /> ``` ```js const button = document.querySelector("input"); button.addEventListener("click", disableButton); function disableButton() { button.disabled = true; button.value = "Disabled"; setTimeout(() => { button.disabled = false; button.value = "Enabled"; }, 2000); } ``` {{EmbedLiveSample("Setting_the_disabled_attribute", 650, 60)}} #### Inheriting the disabled state If the `disabled` attribute isn't specified, the button inherits its `disabled` state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a {{HTMLElement("fieldset")}} element, and then setting `disabled` on the container. The example below shows this in action. This is very similar to the previous example, except that the `disabled` attribute is set on the `<fieldset>` when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed. ```html <fieldset> <legend>Button group</legend> <input type="button" value="Button 1" /> <input type="button" value="Button 2" /> <input type="button" value="Button 3" /> </fieldset> ``` ```js const button = document.querySelector("input"); const fieldset = document.querySelector("fieldset"); button.addEventListener("click", disableButton); function disableButton() { fieldset.disabled = true; setTimeout(() => { fieldset.disabled = false; }, 2000); } ``` {{EmbedLiveSample("Inheriting_the_disabled_state", 650, 100)}} > **Note:** Firefox will, unlike other browsers, by default, [persist the dynamic disabled state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of a {{HTMLElement("button")}} across page loads. Use the [`autocomplete`](/en-US/docs/Web/HTML/Element/button#autocomplete) attribute to control this feature. ## Validation Buttons don't participate in constraint validation; they have no real value to be constrained. ## Examples The below example shows a very simple drawing app created using a {{htmlelement("canvas")}} element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas. ```html <div class="toolbar"> <input type="color" aria-label="select pen color" /> <input type="range" min="2" max="50" value="30" aria-label="select pen size" /><span class="output">30</span> <input type="button" value="Clear canvas" /> </div> <canvas class="myCanvas"> <p>Add suitable fallback here.</p> </canvas> ``` ```css hidden body { background: #ccc; margin: 0; overflow: hidden; } .toolbar { background: #ccc; width: 150px; height: 75px; padding: 5px; } input[type="color"], input[type="button"] { width: 90%; margin: 0 auto; display: block; } input[type="range"] { width: 70%; } span { position: relative; bottom: 5px; } ``` ```js const canvas = document.querySelector(".myCanvas"); const width = (canvas.width = window.innerWidth); const height = (canvas.height = window.innerHeight - 85); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(0 0 0)"; ctx.fillRect(0, 0, width, height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector(".output"); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees) { return (degrees * Math.PI) / 180; } // update sizepicker output value sizePicker.oninput = () => { output.textContent = sizePicker.value; }; // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) => { curX = e.pageX; curY = e.pageY; }; canvas.onmousedown = () => { pressed = true; }; canvas.onmouseup = () => { pressed = false; }; clearBtn.onclick = () => { ctx.fillStyle = "rgb(0 0 0)"; ctx.fillRect(0, 0, width, height); }; function draw() { if (pressed) { ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc( curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false, ); ctx.fill(); } requestAnimationFrame(draw); } draw(); ``` {{EmbedLiveSample("Examples", '100%', 600)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>A string used as the button's label</td> </tr> <tr> <td><strong>Events</strong></td> <td>{{domxref("Element/click_event", "click")}}</td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#type"><code>type</code></a> and <a href="/en-US/docs/Web/HTML/Element/input#value"><code>value</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td>None</td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role"><code>button</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it. - The more modern {{HTMLElement("button")}} element. - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/search/index.md
--- title: <input type="search"> slug: Web/HTML/Element/input/search page-type: html-element browser-compat: html.elements.input.type_search --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`search`** are text fields designed for the user to enter search queries into. These are functionally identical to [`text`](/en-US/docs/Web/HTML/Element/input/text) inputs, but may be styled differently by the {{Glossary("user agent")}}. {{EmbedInteractiveExample("pages/tabbed/input-search.html", "tabbed-standard")}} ## Value The [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string representing the value contained in the search field. You can retrieve this using the [`HTMLInputElement.value`](/en-US/docs/Web/API/HTMLInputElement#value) property in JavaScript. ```js searchTerms = mySearch.value; ``` If no validation constraints are in place for the input (see [Validation](#validation) for more details), the value can be any text string or an empty string (`""`). ## Additional attributes In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, search field inputs support the following attributes. ### list The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum string length (measured in UTF-16 code units) that the user can enter into the search field. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the search field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. ### minlength The minimum string length (measured in UTF-16 code units) that the user can enter into the search field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the search input has no minimum length. The search field will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. ### pattern The `pattern` attribute, when specified, is a regular expression that 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 `'u'` flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. > **Note:** Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section [Specifying a pattern](#specifying_a_pattern) for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ({{cssxref("font")}} settings in use). This does _not_ set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ### spellcheck `spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on {{HTMLElement("input")}} elements. The permitted values for `spellcheck` are: - `false` - : Disable spell checking for this element. - `true` - : Enable spell checking for this element. - "" (empty string) or no value - : Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors. An input field can have spell checking enabled if it doesn't have the [readonly](#readonly) attribute set and is not disabled. The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the {{Glossary("user agent", "user agent's")}} preferences override the setting. ## Non-standard attributes The following non-standard attributes are available to search input fields. As a general rule, you should avoid using them unless it can't be helped. ### autocorrect A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: - `on` - : Enable automatic correction of typos, as well as processing of text substitutions if any are configured. - `off` - : Disable automatic correction and text substitutions. ### incremental The Boolean attribute `incremental` is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the {{Glossary("user agent")}} to process the input as a live search. As the user edits the value of the field, the user agent sends {{domxref("HTMLInputElement/search_event", "search")}} events to the {{domxref("HTMLInputElement")}} object representing the search box. This allows your code to update the search results in real time as the user edits the search. If `incremental` is not specified, the {{domxref("HTMLInputElement/search_event", "search")}} event is only sent when the user explicitly initiates a search (such as by pressing the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field). The `search` event is rate-limited so that it is not sent more frequently than an implementation-defined interval. ### mozactionhint {{deprecated_inline}} A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field. <strong>Deprecated: Use [`enterkeyhint`](/en-US/docs/Web/HTML/Global_attributes#enterkeyhint) instead.</strong> ### results The `results` attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the {{HTMLElement("input")}} element's natively-provided drop-down menu of previous search queries. The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser's default maximum number of entries is used. ## Using search inputs `<input>` elements of type `search` are very similar to those of type `text`, except that they are specifically intended for handling search terms. They are basically equivalent in behavior, but user agents may choose to style them differently by default (and, of course, sites may use stylesheets to apply custom styles to them). ### Basic example ```html <form> <div> <input type="search" id="mySearch" name="q" /> <button>Search</button> </div> </form> ``` This renders like so: {{EmbedLiveSample("Basic_example", 600, 40)}} `q` is the most common `name` given to search inputs, although it's not mandatory. When submitted, the data name/value pair sent to the server will be `q=searchterm`. > **Note:** You must remember to set a [`name`](/en-US/docs/Web/HTML/Element/input#name) for your input, otherwise nothing will be submitted. ### Differences between search and text types The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired, in Chrome this action is also triggered when pressing escape. The following screenshot comes from Chrome: ![Focused search input, with focus ring, with the text 'cats'. There is an x icon in the input abutting the right side.](chrome-cross-icon.png) In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox: ![An input in error state with a red focus ring. The user has entered the letter 'h'. A pop-up selection list is open directly under the input box with two options: hello and hermansje.](firefox-auto-complete.png)At this point, let's look at some useful techniques you can apply to your search forms. ### Setting placeholders You can provide a useful placeholder inside your search input that could give a hint on what to do using the [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) attribute. Look at the following example: ```html <form> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" /> <button>Search</button> </div> </form> ``` You can see how the placeholder is rendered below: {{EmbedLiveSample("Setting_placeholders", 600, 40)}} ### Search form labels and accessibility One problem with search forms is their accessibility; a common design practice is not to provide a label for the search field (although there might be a magnifying glass icon or similar), as the purpose of a search form is normally fairly obvious for sighted users due to placement ([this example shows a typical pattern](https://mdn.github.io/learning-area/accessibility/aria/website-aria-roles/)). This could, however, cause confusion for screen reader users, since they will not have any verbal indication of what the search input is. One way around this that won't impact on your visual design is to use [WAI-ARIA](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) features: - A `role` attribute of value `search` on the `<form>` element will cause screen readers to announce that the form is a search form. - If that isn't enough, you can use an [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute on the {{HTMLElement("input")}} itself. This should be a descriptive text label that will be read out by the screen reader; it's used as a non-visual equivalent to `<label>`. Let's have a look at an example: ```html <form role="search"> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" aria-label="Search through site content" /> <button>Search</button> </div> </form> ``` You can see how this is rendered below: {{EmbedLiveSample("Search_form_labels_and_accessibility", 600, 40)}} There is no visual difference from the previous example, but screen reader users have way more information available to them. > **Note:** See [Signposts/Landmarks](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics#signpostslandmarks) for more information about such accessibility features. ### Physical input element size The physical size of the input box can be controlled using the [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the search box is 30 characters wide: ```html <form> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" size="30" /> <button>Search</button> </div> </form> ``` The result is this wider input box: {{ EmbedLiveSample('Physical_input_element_size', 600, 40) }} ## Validation `<input>` elements of type `search` have the same validation features available to them as regular `text` inputs. It is less likely that you'd want to use validation features in general for search boxes. In many cases, users should just be allowed to search for anything, but there are a few cases to consider, such as searches against data of a known format. > **Note:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### A note on styling There are useful pseudo-classes available for styling valid/invalid form elements: {{cssxref(":valid")}} and {{cssxref(":invalid")}}. In this section, we'll use the following CSS, which will place a check (tick) next to inputs containing valid values, and a cross next to inputs containing invalid values. ```css input:invalid ~ span::after { content: "✖"; padding-left: 5px; position: absolute; } input:valid ~ span::after { content: "✓"; padding-left: 5px; position: absolute; } ``` The technique also requires a {{htmlelement("span")}} element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well. ### Making input required You can use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute as an easy way of making entering a value required before form submission is allowed: ```html <form> <div> <input type="search" id="mySearch" name="q" placeholder="Search the site…" required /> <button>Search</button> <span class="validity"></span> </div> </form> ``` ```css hidden input { margin-right: 10px; } input:invalid ~ span::after { content: "✖"; padding-left: 5px; position: absolute; } input:valid ~ span::after { content: "✓"; padding-left: 5px; position: absolute; } ``` This renders like so: {{ EmbedLiveSample('Making_input_required', 600, 40) }} In addition, if you try to submit the form with no search term entered into it, the browser will show a message. The following example is from Firefox: ![form field with attached message that says Please fill out this field](firefox-required-message.png) Different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below examples. ### Input value length You can specify a minimum length, in characters, for the entered value using the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute; similarly, use [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) to set the maximum length of the entered value. The example below requires that the entered value be 4–8 characters in length. ```html <form> <div> <label for="mySearch">Search for user</label> <input type="search" id="mySearch" name="q" placeholder="User IDs are 4–8 characters in length" required size="30" minlength="4" maxlength="8" /> <button>Search</button> <span class="validity"></span> </div> </form> ``` ```css hidden input { margin-right: 10px; } input:invalid ~ span::after { content: "✖"; padding-left: 5px; position: absolute; } input:valid ~ span::after { content: "✓"; padding-left: 5px; position: absolute; } ``` This renders like so: {{ EmbedLiveSample('Input_value_length', 600, 40) }} If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to go beyond 8 characters in length, the browser won't let you. ### 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 follow 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). Let's look at an example. Say we wanted to provide a product ID search form, and the IDs were all codes of two letters followed by four numbers. The following example covers it: ```html <form> <div> <label for="mySearch">Search for product by ID:</label> <input type="search" id="mySearch" name="q" placeholder="two letters followed by four numbers" required size="30" pattern="[A-z]{2}[0-9]{4}" /> <button>Search</button> <span class="validity"></span> </div> </form> ``` ```css hidden input { margin-right: 10px; } input:invalid ~ span::after { content: "✖"; padding-left: 5px; position: absolute; } input:valid ~ span::after { content: "✓"; padding-left: 5px; position: absolute; } ``` This renders like so: {{ EmbedLiveSample('Specifying_a_pattern', 600, 40) }} ## Examples You can see a good example of a search form used in context at our [website-aria-roles](https://github.com/mdn/learning-area/tree/main/accessibility/aria/website-aria-roles) example ([see it live](https://mdn.github.io/learning-area/accessibility/aria/website-aria-roles/)). ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing the value contained in the search field. </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported Common Attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#maxlength"><code>maxlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#minlength"><code>minlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#pattern"><code>pattern</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#required"><code>required</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#size"><code>size</code></a>. </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}, {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}. </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td>with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/searchbox_role">searchbox</a></code></td> <td>with <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role">combobox</a></code></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML Forms](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface it's based upon - [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/text/index.md
--- title: <input type="text"> slug: Web/HTML/Element/input/text page-type: html-element browser-compat: html.elements.input.type_text --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`text`** create basic single-line text fields. {{EmbedInteractiveExample("pages/tabbed/input-text.html", "tabbed-shorter")}} ## Value The [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute is a string that contains the current value of the text entered into the text field. You can retrieve this using the {{domxref("HTMLInputElement")}} `value` property in JavaScript. ```js let theText = myTextInput.value; ``` If no validation constraints are in place for the input (see [Validation](#validation) for more details), the value may be an empty string (`""`). ## Additional attributes In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, text inputs support the following attributes. ### `list` The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### `maxlength` The maximum string length (measured in UTF-16 code units) that the user can enter into the `text` input. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `text` input has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/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. ### `minlength` The minimum string length (measured in UTF-16 code units) that the user can enter into the `text` input. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the `text` input has no minimum length. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### `pattern` The `pattern` attribute, when specified, is a regular expression that 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 `'u'` flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. > **Note:** Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See [Specifying a pattern](#specifying_a_pattern) for further details and an example. ### `placeholder` The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` accessibility concerns](/en-US/docs/Web/HTML/Element/input#accessibility_concerns) for more information. ### `readonly` A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### `size` The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ({{cssxref("font")}} settings in use). This does _not_ set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ### `spellcheck` `spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on {{HTMLElement("input")}} elements. The permitted values for `spellcheck` are: - `false` - : Disable spell checking for this element. - `true` - : Enable spell checking for this element. - `""` (empty string) or no value - : Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors. An input field can have spell checking enabled if it doesn't have the [readonly](#readonly) attribute set and is not disabled. The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the {{Glossary("user agent", "user agent's")}} preferences override the setting. ## Non-standard attributes The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. ### `autocorrect` A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: - `on` - : Enable automatic correction of typos, as well as processing of text substitutions if any are configured. - `off` - : Disable automatic correction and text substitutions. ### `mozactionhint` {{deprecated_inline}} A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field. <strong>Deprecated: Use [`enterkeyhint`](/en-US/docs/Web/HTML/Global_attributes#enterkeyhint) instead.</strong> ## Using text inputs `<input>` elements of type `text` create basic, single-line inputs. You should use them anywhere you want the user to enter a single-line value and there isn't a more specific input type available for collecting that value (for example, if it's a [date](/en-US/docs/Web/HTML/Element/input/datetime-local), [URL](/en-US/docs/Web/HTML/Element/input/url), [email](/en-US/docs/Web/HTML/Element/input/email), or [search term](/en-US/docs/Web/HTML/Element/input/search), you've got better options available). ### Basic example ```html <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" /> </div> <div> <button>Submit</button> </div> </form> ``` This renders like so: {{EmbedLiveSample("Basic_example", 600, 80)}} When submitted, the data name/value pair sent to the server will be `name=Chris` (if "Chris" was entered as the input value before submission). You must remember to include [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute on the {{HTMLElement("input")}} element, otherwise the text field's value won't be included with the submitted data. ### Setting placeholders You can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) attribute. Look at the following example: ```html <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" placeholder="Lower case, all one word" /> </div> <div> <button>Submit</button> </div> </form> ``` You can see how the placeholder is rendered below: {{EmbedLiveSample("Setting_placeholders", 600, 80)}} The placeholder is typically rendered in a lighter color than the element's foreground color, and automatically vanishes when the user begins to enter text into the field (or whenever the field has a value set programmatically by setting its `value` attribute). ### Physical input element size The physical size of the input box can be controlled using the [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute. With it, you can specify the number of characters the text input can display at a time. This affects the width of the element, letting you specify the width in terms of characters rather than pixels. In this example, for instance, the input is 30 characters wide: ```html <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" placeholder="Lower case, all one word" size="30" /> </div> <div> <button>Submit</button> </div> </form> ``` {{EmbedLiveSample('Physical_input_element_size', 600, 80)}} ## Validation `<input>` elements of type `text` have no automatic validation applied to them (since a basic text input needs to be capable of accepting any arbitrary string), but there are some client-side validation options available, which we'll discuss below. > **Note:** HTML form validation is _not_ a substitute for server-scripts that ensure the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### A note on styling There are useful pseudo-classes available for styling form elements to help the user see when their values are valid or invalid. These are {{cssxref(":valid")}} and {{cssxref(":invalid")}}. In this section, we'll use the following CSS, which will place a check (tick) mark next to inputs containing valid values, and a cross (X) next to inputs containing invalid values. ```css div { margin-bottom: 10px; position: relative; } 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; } ``` The technique also requires a {{htmlelement("span")}} element to be placed after the form element, which acts as a holder for the icons. This was necessary because some input types on some browsers don't display icons placed directly after them very well. ### Making input required You can use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute as an easy way of making entering a value required before form submission is allowed: ```html <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` ```css hidden div { margin-bottom: 10px; position: relative; } 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('Making_input_required', 600, 100)}} If you try to submit the form with no search term entered into it, the browser will show an error message. ### Input value length You can specify a minimum length (in characters) for the entered value using the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute; similarly, use [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) to set the maximum length of the entered value, in characters. The example below requires that the entered value be 4–8 characters in length. ```html <form> <div> <label for="uname">Choose a username: </label> <input type="text" id="uname" name="name" required size="10" placeholder="Username" minlength="4" maxlength="8" /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` ```css hidden div { margin-bottom: 10px; position: relative; } 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('Input_value_length', 600, 100)}} If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to enter more than 8 characters, the browser won't let you. > **Note:** If you specify a `minlength` but do not specify `required`, the input is considered valid, since the user is not required to specify a value. ### 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}" /> <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, 130)}} ## Examples You can see good examples of text inputs used in context in our [Your first HTML form](/en-US/docs/Learn/Forms/Your_first_form) and [How to structure an HTML form](/en-US/docs/Learn/Forms/How_to_structure_a_web_form) articles. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing the text contained in the text field. </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported Common Attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#maxlength"><code>maxlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#minlength"><code>minlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#pattern"><code>pattern</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#required"><code>required</code></a> and <a href="/en-US/docs/Web/HTML/Element/input#size"><code>size</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}} and {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}. </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td>with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code></td> <td>with <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role">combobox</a></code></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML Forms](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface it's based upon. - [`<input type="search">`](/en-US/docs/Web/HTML/Element/input/search) - {{HTMLElement("textarea")}}: Multi-line text input - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/email/index.md
--- title: <input type="email"> slug: Web/HTML/Element/input/email page-type: html-element browser-compat: html.elements.input.type_email --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`email`** are used to let the user enter and edit an email address, or, if the [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) attribute is specified, a list of email addresses. {{EmbedInteractiveExample("pages/tabbed/input-email.html", "tabbed-shorter")}} The input value is automatically validated to ensure that it's either empty or a properly-formatted email address (or list of addresses) before the form can be submitted. The {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid email address or not. ## Value The {{HTMLElement("input")}} element's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string which is automatically validated as conforming to email syntax. More specifically, there are three possible value formats that will pass validation: 1. An empty string ("") indicating that the user did not enter a value or that the value was removed. 2. A single properly-formed email address. This doesn't necessarily mean the email address exists, but it is at least formatted correctly. In simple terms, this means `username@domain` or `[email protected]`. There's more to it than that, of course; see [Validation](#validation) for a {{Glossary("regular expression")}} that matches the email address validation algorithm. 3. If and only if the [`multiple`](/en-US/docs/Web/HTML/Element/input#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. See [Validation](#validation) for details on how email addresses are validated to ensure that they're formatted properly. ## Additional attributes In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, `email` inputs support the following attributes. ### list The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum string length (measured in UTF-16 code units) that the user can enter into the `email` input. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `email` input has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/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. ### minlength The minimum string length (measured in UTF-16 code units) that the user can enter into the `email` input. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the `email` input has no minimum length. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### multiple A Boolean attribute which, if present, indicates that the user can enter a list of multiple email addresses, separated by commas and, optionally, whitespace characters. See [Allowing multiple email addresses](#allowing_multiple_email_addresses) for an example, or [HTML attribute: multiple](/en-US/docs/Web/HTML/Attributes/multiple) for more details. > **Note:** Normally, if you specify the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, the user must enter a valid email address for the field to be considered valid. However, if you add the `multiple` attribute, a list of zero email addresses (an empty string, or one which is entirely whitespace) is a valid value. In other words, the user does not have to enter even one email address when `multiple` is specified, regardless of the value of `required`. ### pattern The `pattern` attribute, when specified, is a regular expression that 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 `'u'` flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. > **Note:** Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section [Pattern validation](#pattern_validation) for details and an example. ### `placeholder` The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for more information. ### `readonly` A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### `size` The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ({{cssxref("font")}} settings in use). This does _not_ set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ## Using email inputs Email addresses are among the most frequently-inputted textual data forms on the web; they're used when logging into websites, when requesting information, to allow order confirmation, for webmail, and so forth. As such, the `email` input type can make your job as a web developer much easier since it can help simplify your work when building the user interface and logic for email addresses. When you create an email input with the proper `type` value, `email`, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate email address. This can help avoid cases in which the user mistypes their address, or provides an invalid address. It's important, however, to note that this is not enough to ensure that the specified text is an email address which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be an email address. > **Note:** It's also crucial to remember that a user can tinker with your HTML behind the scenes, so your site _must not_ use this validation for any security purposes. You _must_ verify the email address on the server side of any transaction in which the provided text may have any security implications of any kind. ### A simple email input Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. The specification does, however, allow browsers latitude on this. For example, the element could be integrated with the user's device's built-in address book to allow picking email addresses from that list. In its most basic form, an `email` input can be implemented like this: ```html <input id="emailAddress" type="email" /> ``` {{ EmbedLiveSample('A_simple_email_input', 600, 40) }} Notice that it's considered valid when empty and when a single validly-formatted email address is entered, but is otherwise not considered valid. By adding the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, only validly-formed email addresses are allowed; the input is no longer considered valid when empty. ### Allowing multiple email addresses By adding the [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) Boolean attribute, the input can be configured to accept multiple email addresses. ```html <input id="emailAddress" type="email" multiple /> ``` {{ EmbedLiveSample('Allowing multiple email addresses', 600, 40) }} The input is now considered valid when a single email address is entered, or when any number of email addresses separated by commas and, optionally, some number of whitespace characters are present. > **Note:** When `multiple` is used, the value _is_ allowed to be empty. Some examples of valid strings when `multiple` is specified: - `""` - `"me@example"` - `"[email protected]"` - `"[email protected],[email protected]"` - `"[email protected], [email protected]"` - `"[email protected],[email protected], [email protected]"` Some examples of invalid strings: - `","` - `"me"` - `"[email protected] [email protected]"` ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each {{HTMLElement("input")}}. This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have an `email` input with the placeholder `[email protected]`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ```html <input type="email" placeholder="[email protected]" /> ``` {{ EmbedLiveSample('Placeholders', 600, 40) }} ### Controlling the input size You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself. #### Physical input element size The physical size of the input box can be controlled using the [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example the `email` edit box is 15 characters wide: ```html <input type="email" size="15" /> ``` {{ EmbedLiveSample('Physical_input_element_size', 600, 40) }} #### Element value length The `size` is separate from the length limitation on the entered email address itself so that you can have fields fit in a small space while still allowing longer email address strings to be entered. You can specify a minimum length, in characters, for the entered email address using the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute; similarly, use [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) to set the maximum length of the entered email address. The example below creates a 32 character-wide email address entry box, requiring that the contents be no shorter than 3 characters and no longer than 64 characters. ```html <input type="email" size="32" minlength="3" maxlength="64" /> ``` {{EmbedLiveSample("Element_value_length", 600, 40) }} ### Providing default options #### Providing a single default using the value attribute As always, you can provide a default value for an `email` input box by setting its [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute: ```html <input type="email" value="[email protected]" /> ``` {{EmbedLiveSample("Providing_a_single_default_using_the_value_attribute", 600, 40)}} #### Offering suggested values Taking it a step further, you can provide a list of default options from which the user can select by specifying the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute. This doesn't limit the user to those options, but does allow them to select commonly-used email addresses more quickly. This also offers hints to [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete). The `list` attribute specifies the ID of a {{HTMLElement("datalist")}}, which in turn contains one {{HTMLElement("option")}} element per suggested value; each `option`'s `value` is the corresponding suggested value for the email entry box. ```html <input type="email" size="40" list="defaultEmails" /> <datalist id="defaultEmails"> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> </datalist> ``` {{EmbedLiveSample("Offering_suggested_values", 600, 40)}} With the {{HTMLElement("datalist")}} element and its {{HTMLElement("option")}}s in place, the browser will offer the specified values as potential values for the email address; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested email addresses. Then, as the user types, the list is filtered to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value. ## Validation There are two levels of content validation available for `email` inputs. First, there's the standard level of validation offered to all {{HTMLElement("input")}}s, which automatically ensures that the contents meet the requirements to be a valid email address. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any. > **Warning:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format.It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it completely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### Basic validation Browsers automatically provide validation to ensure that only text that matches the standard format for Internet email addresses is entered into the input box. Browsers use an algorithm equivalent to the following regular expression: ```js /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; ``` To learn more about how form validation works and how to take advantage of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether the current value is valid, see [Form data validation](/en-US/docs/Learn/Forms/Form_validation). > **Note:** There are known specification issues related to international domain names and the validation of email addresses in HTML. See [W3C bug 15489](https://www.w3.org/Bugs/Public/show_bug.cgi?id=15489) for details. ### Pattern validation If you need the entered email address to be restricted further than just "any string that looks like an email address," you can use the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute to specify a {{Glossary("regular expression")}} the value must match for it to be valid. If the [`multiple`](/en-US/docs/Web/HTML/Element/input#multiple) attribute is specified, each individual item in the comma-delineated list of values must match the {{Glossary("regular expression")}}. For example, let's say you're building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their email address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid email address, but for security purposes, we require that the address be an internal corporate email address. Since inputs of type `email` validate against both the standard email address validation _and_ the specified [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern), you can implement this easily. Let's see how: ```css hidden body { font: 16px sans-serif; } .emailBox { padding-bottom: 20px; } .messageBox { padding-bottom: 20px; } label { line-height: 22px; } label::after { content: ":"; } ``` ```html <form> <div class="emailBox"> <label for="emailAddress">Your email address</label><br /> <input id="emailAddress" type="email" size="64" maxlength="64" required placeholder="[email protected]" pattern=".+@beststartupever\.com" title="Please provide only a Best Startup Ever corporate email address" /> </div> <div class="messageBox"> <label for="message">Request</label><br /> <textarea id="message" cols="80" rows="8" required placeholder="My shoes are too tight, and I have forgotten how to dance."></textarea> </div> <input type="submit" value="Send Request" /> </form> ``` {{EmbedLiveSample("Pattern_validation", 700, 300)}} Our {{HTMLElement("form")}} contains one {{HTMLElement("input")}} of type `email` for the user's email address, a {{HTMLElement("textarea")}} to enter their message for IT into, and an `<input>` of type [`"submit"`](/en-US/docs/Web/HTML/Element/input/submit), which creates a button to submit the form. Each text entry box has a {{HTMLElement("label")}} associated with it to let the user know what's expected of them. Let's take a closer look at the email address entry box. Its [`size`](/en-US/docs/Web/HTML/Element/input#size) and [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) attributes are both set to 64 in order to show room for 64 characters worth of email address, and to limit the number of characters actually entered to a maximum of 64. The [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute is specified, making it mandatory that a valid email address be provided. An appropriate [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) is provided—`[email protected]`—to demonstrate what constitutes a valid entry. This string demonstrates both that an email address should be entered, and suggests that it should be a corporate beststartupever.com account. This is in addition to the fact that using type `email` will validate the text to ensure that it's formatted like an email address. If the text in the input box isn't an email address, you'll get an error message that looks something like this: ![Invalid email address in error state with a popout from the input reading 'please enter an email address'.](enter-valid-email-address.png) If we left things at that, we would at least be validating on legitimate email addresses. But we want to go one step farther: we want to make sure that the email address is in fact in the form "[email protected]". This is where we'll use [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern). We set `pattern` to `[email protected]`. This simple regular expression requests a string that consists of at least one character of any kind, then an "@" followed by the domain name "beststartupever.com". Note that this is not even close to an adequate filter for valid email addresses; it would allow things such as " @beststartupever.com" (note the leading space) or "@@beststartupever.com", neither of which is valid. However, the browser runs both the standard email address filter _and_ our custom pattern against the specified text. As a result, we wind up with a validation which says "make sure this resembles a valid email address, and if it is, make sure it's also a beststartupever.com address." It's advisable to use the [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute along with `pattern`. If you do, the `title` _must_ describe the pattern. That is, it should explain what format the data should take on, rather than any other information. That's because the `title` may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified `title`. If your `title` is something like "Email address", the result would be the message "The entered text doesn't match the required pattern. Email address", which isn't very good. That's why, instead, we specify the string "Please provide only a Best Startup Ever corporate email address" By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address." ![A valid email address, but the input is in error state with a popout from the input reading 'The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate email address.'](email-pattern-match-bad.png) > **Note:** If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem. ## Examples Here we have an email input with the ID `emailAddress` which is allowed to be up to a maximum of 256 characters long. The input box itself is physically 64 characters wide, and displays the text `[email protected]` as a placeholder anytime the field is empty. In addition, by using the [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) attribute, the box is configured to allow the user to enter zero or more email addresses, separated by commas, as described in [Allowing multiple email addresses](#allowing_multiple_email_addresses). As a final touch, the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute contains the ID of a {{HTMLElement("datalist")}} whose {{HTMLElement("option")}}s specify a set of suggested values the user can choose from. As an added touch, the {{HTMLElement("label")}} element is used to establish a label for the email entry box, with its [`for`](/en-US/docs/Web/HTML/Element/label#for) attribute referencing the `emailAddress` ID of the {{HTMLElement("input")}} element. By associating the two elements in this way, clicking on the label will focus the input element. ```html <label for="emailAddress">Email</label><br /> <input id="emailAddress" type="email" placeholder="[email protected]" list="defaultEmails" size="64" maxlength="256" multiple /> <datalist id="defaultEmails"> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> <option value="[email protected]"></option> </datalist> ``` {{EmbedLiveSample('Examples', 600, 80)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing an email address, or empty </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported Common Attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#maxlength"><code>maxlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#minlength"><code>minlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#multiple"><code>multiple</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#name"><code>name</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#pattern"><code>pattern</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#required"><code>required</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#size"><code>size</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#type"><code>type</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>list</code> and <code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td> with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code><br /> with <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role">combobox</a></code> </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML forms guide](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} - [`<input type="tel">`](/en-US/docs/Web/HTML/Element/input/tel) - [`<input type="url">`](/en-US/docs/Web/HTML/Element/input/url) - Attributes: - [`list`](/en-US/docs/Web/HTML/Element/input#list) - [`minlength`](/en-US/docs/Web/HTML/Attributes/minlength) - [`maxlength`](/en-US/docs/Web/HTML/Attributes/maxlength) - [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) - [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) - [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) - [`readonly`](/en-US/docs/Web/HTML/Attributes/readonly) - [`size`](/en-US/docs/Web/HTML/Attributes/size) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/checkbox/index.md
--- title: <input type="checkbox"> slug: Web/HTML/Element/input/checkbox page-type: html-element browser-compat: html.elements.input.type_checkbox --- {{HTMLSidebar}} {{htmlelement("input")}} elements of type **`checkbox`** are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. The exact appearance depends upon the operating system configuration under which the browser is running. Generally this is a square but it may have rounded corners. A checkbox allows you to select single values for submission in a form (or not). {{EmbedInteractiveExample("pages/tabbed/input-checkbox.html", "tabbed-standard")}} > **Note:** [Radio buttons](/en-US/docs/Web/HTML/Element/input/radio) are similar to checkboxes, but with an important distinction — [same-named radio buttons](/en-US/docs/Web/HTML/Element/input/radio#defining_a_radio_group) are grouped into a set in which only one radio button can be selected at a time, whereas checkboxes allow you to turn single values on and off. Where multiple same-named controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. ## Value A string representing the value of the checkbox. This is not displayed on the client-side, but on the server this is the `value` given to the data submitted with the checkbox's `name`. Take the following example: ```html <form> <div> <input type="checkbox" id="subscribeNews" name="subscribe" value="newsletter" /> <label for="subscribeNews">Subscribe to newsletter?</label> </div> <div> <button type="submit">Subscribe</button> </div> </form> ``` In this example, we've got a name of `subscribe`, and a value of `newsletter`. When the form is submitted, the data name/value pair will be `subscribe=newsletter`. If the `value` attribute was omitted, the default value for the checkbox is `on`, so the submitted data in that case would be `subscribe=on`. > **Note:** If a checkbox is unchecked when its form is submitted, neither the name nor the value is submitted to the server. There is no HTML-only method of representing a checkbox's unchecked state (e.g. `value=unchecked`). If you wanted to submit a default value for the checkbox when it is unchecked, you could include JavaScript to create a {{HTMLElement("input/hidden", '&lt;input type="hidden"&gt;')}} within the form with a value indicating an unchecked state. ## Additional attributes In addition to the [common attributes](/en-US/docs/Web/HTML/Element/input#attributes) shared by all {{HTMLElement("input")}} elements, "`checkbox`" inputs support the following attributes. - `checked` - : A [boolean](/en-US/docs/Glossary/Boolean/HTML) attribute indicating whether this checkbox is checked by default (when the page loads). It does _not_ indicate whether this checkbox is currently checked: if the checkbox's state is changed, this content attribute does not reflect the change. (Only the {{domxref("HTMLInputElement")}}'s `checked` IDL attribute is updated.) > **Note:** Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently `checked`. If it is, then the value of the checkbox's `value` attribute is reported as the input's value, or `on` if no `value` is set. > Unlike other browsers, Firefox by default [persists the dynamic checked state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` across page loads. Use the [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) attribute to control this feature. - `value` - : The `value` attribute is one which all {{HTMLElement("input")}}s share; however, it serves a special purpose for inputs of type `checkbox`: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the `value` attribute. If the `value` is not otherwise specified, it is the string `on` by default. This is demonstrated in the section [Value](#value) above. ## Using checkbox inputs We already covered the most basic use of checkboxes above. Let's now look at the other common checkbox-related features and techniques you'll need. ### Handling multiple checkboxes The example we saw above only contained one checkbox; in real-world situations you'll be likely to encounter multiple checkboxes. If they are completely unrelated, then you can just deal with them all separately, as shown above. However, if they're all related, things are not quite so simple. For example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the [Examples](#examples) section). ```html <fieldset> <legend>Choose your interests</legend> <div> <input type="checkbox" id="coding" name="interest" value="coding" /> <label for="coding">Coding</label> </div> <div> <input type="checkbox" id="music" name="interest" value="music" /> <label for="music">Music</label> </div> </fieldset> ``` {{EmbedLiveSample('Handling_multiple_checkboxes', 600, 100)}} In this example you will see that we've given each checkbox the same `name`. If both checkboxes are checked and then the form is submitted, you'll get a string of name/value pairs submitted like this: `interest=coding&interest=music`. When this string reaches the server, you need to parse it other than as an associative array, so all values, not only the last value, of `interest` are captured. For one technique used with Python, see [Handle Multiple Checkboxes with a Single Serverside Variable](https://stackoverflow.com/questions/18745456/handle-multiple-checkboxes-with-a-single-serverside-variable), for example. ### Checking boxes by default To make a checkbox checked by default, you give it the `checked` attribute. See the below example: ```html <fieldset> <legend>Choose your interests</legend> <div> <input type="checkbox" id="coding" name="interest" value="coding" checked /> <label for="coding">Coding</label> </div> <div> <input type="checkbox" id="music" name="interest" value="music" /> <label for="music">Music</label> </div> </fieldset> ``` {{EmbedLiveSample('Checking_boxes_by_default', 600, 100)}} ### Providing a bigger hit area for your checkboxes In the above examples, you may have noticed that you can toggle a checkbox by clicking on its associated {{htmlelement("label")}} element as well as on the checkbox itself. This is a really useful feature of HTML form labels that makes it easier to click the option you want, especially on small-screen devices like smartphones. Beyond accessibility, this is another good reason to properly set up `<label>` elements on your forms. ### Indeterminate state checkboxes In addition to the checked and unchecked states, there is a third state a checkbox can be in: **indeterminate**. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the {{domxref("HTMLInputElement")}} object's `indeterminate` property via JavaScript (it cannot be set using an HTML attribute): ```js inputInstance.indeterminate = true; ``` A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers. There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked, and if they're all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state. This can be seen in the below example (thanks to [CSS Tricks](https://css-tricks.com/indeterminate-checkboxes/) for the inspiration). In this example we keep track of the ingredients we are collecting for a recipe. When you check or uncheck an ingredient's checkbox, a JavaScript function checks the total number of checked ingredients: - If none are checked, the recipe name's checkbox is set to unchecked. - If one or two are checked, the recipe name's checkbox is set to `indeterminate`. - If all three are checked, the recipe name's checkbox is set to `checked`. So in this case the `indeterminate` state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ```js const overall = document.querySelector("#enchantment"); const ingredients = document.querySelectorAll("ul input"); overall.addEventListener("click", (e) => { e.preventDefault(); }); for (const ingredient of ingredients) { ingredient.addEventListener("click", updateDisplay); } function updateDisplay() { let checkedCount = 0; for (const ingredient of ingredients) { if (ingredient.checked) { checkedCount++; } } if (checkedCount === 0) { overall.checked = false; overall.indeterminate = false; } else if (checkedCount === ingredients.length) { overall.checked = true; overall.indeterminate = false; } else { overall.checked = false; overall.indeterminate = true; } } ``` {{EmbedGHLiveSample("learning-area/html/forms/indeterminate-example/index.html", '100%', 200)}} > **Note:** If you submit a form with an indeterminate checkbox, the same thing happens as if the checkbox were unchecked — no data is submitted to represent the checkbox. ## Validation Checkboxes do support [validation](/en-US/docs/Web/HTML/Constraint_validation) (offered to all {{HTMLElement("input")}}s). However, most of the {{domxref("ValidityState")}}s will always be `false`. If the checkbox has the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, but is not checked, then {{domxref("ValidityState.valueMissing")}} will be `true`. ## Examples The following example is an extended version of the "multiple checkboxes" example we saw above — it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option. This is achieved with a simple block of JavaScript. The example includes implicit labels, with the `<input>` directly inside the `<label>`. The text input, without a visible label, includes the [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute which provides its accessible name. This example also includes some CSS to improve the styling. ### HTML ```html <form> <fieldset> <legend>Choose your interests</legend> <div> <label> <input type="checkbox" id="coding" name="interest" value="coding" /> Coding </label> </div> <div> <label> <input type="checkbox" id="music" name="interest" value="music" /> Music </label> </div> <div> <label> <input type="checkbox" id="art" name="interest" value="art" /> Art </label> </div> <div> <label> <input type="checkbox" id="sports" name="interest" value="sports" /> Sports </label> </div> <div> <label> <input type="checkbox" id="cooking" name="interest" value="cooking" /> Cooking </label> </div> <div> <label> <input type="checkbox" id="other" name="interest" value="other" /> Other </label> <input type="text" id="otherValue" name="other" aria-label="Other interest" /> </div> <div> <button type="submit">Submit form</button> </div> </fieldset> </form> ``` ### CSS ```css html { font-family: sans-serif; } form { width: 600px; margin: 0 auto; } div { margin-bottom: 10px; } fieldset { background: cyan; border: 5px solid blue; } legend { padding: 10px; background: blue; color: cyan; } ``` ### JavaScript ```js const otherCheckbox = document.querySelector("#other"); const otherText = document.querySelector("#otherValue"); otherText.style.visibility = "hidden"; otherCheckbox.addEventListener("change", () => { if (otherCheckbox.checked) { otherText.style.visibility = "visible"; otherText.value = ""; } else { otherText.style.visibility = "hidden"; } }); ``` {{EmbedLiveSample('Examples', '100%', 300)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing the value of the checkbox. </td> </tr> <tr> <td><strong>Events</strong></td> <td>{{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}}</td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td><code>checked</code></td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code><a href="#checked">checked</a></code>, <code><a href="#indeterminate">indeterminate</a></code> and <code><a href="#value">value</a></code> </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role"><code>checkbox</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref(":checked")}}, {{cssxref(":indeterminate")}}: CSS selectors that let you style checkboxes based on their current state - {{domxref("HTMLInputElement")}}: HTML DOM API that implements the `<input>` element - [CSS property compatibility table for form controls](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/number/index.md
--- title: <input type="number"> slug: Web/HTML/Element/input/number page-type: html-element browser-compat: html.elements.input.type_number --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`number`** are used to let the user enter a number. They include built-in validation to reject non-numerical entries. The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by tapping with a fingertip. {{EmbedInteractiveExample("pages/tabbed/input-number.html", "tabbed-shorter")}} On browsers that don't support inputs of type `number`, a `number` input falls back to type `text`. ## Value A number representing the value of the number entered into the input. You can set a default value for the input by including a number inside the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute, like so: ```html <input id="number" type="number" value="42" /> ``` {{EmbedLiveSample('Value', 600, 40)}} ## Additional attributes In addition to the attributes commonly supported by all {{HTMLElement("input")}} types, inputs of type `number` support these attributes. ### `list` The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### `max` The maximum value to accept for this input. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element exceeds this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `max` attribute isn't a number, then the element has no maximum value. This value must be greater than or equal to the value of the `min` attribute. ### `min` The minimum value to accept for this input. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) of the element is less than this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If a value is specified for `min` that isn't a valid number, the input has no minimum value. This value must be less than or equal to the value of the `max` attribute. ### `placeholder` The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for more information. ### `readonly` A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### `step` The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. The default stepping value for `number` inputs is `1`, allowing only integers to be entered—_unless_ the stepping base is not an integer. ## Using number inputs The `number` input type should only be used for incremental numbers, especially when spinbutton incrementing and decrementing are helpful to user experience. The `number` input type is not appropriate for values that happen to only consist of numbers but aren't strictly speaking a number, such as postal codes in many countries or credit card numbers. For non-numeric inputs, consider using a different input type, such as [`<input type="tel">`](/en-US/docs/Web/HTML/Element/input/tel) or other {{HTMLElement('input')}} type with the [`inputmode`](/en-US/docs/Web/HTML/Global_attributes#inputmode) attribute: ```html <input type="text" inputmode="numeric" pattern="\d*" /> ``` `<input type="number">` elements can help simplify your work when building the user interface and logic for entering numbers into a form. When you create a number input with the proper `type` value, `number`, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down. > **Warning:** Logically, you should not be able to enter characters inside a number input other than numbers. Some browsers allow invalid characters, others do not; see [Firefox bug 1398528](https://bugzil.la/1398528). > **Note:** A user can tinker with your HTML behind the scenes, so your site _must not_ use simple client-side validation for any security purposes. You _must_ verify on the server side any transaction in which the provided value may have security implications of any kind. Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value. ### A simple number input In its most basic form, a number input can be implemented like this: ```html <label for="ticketNum">Number of tickets you would like to buy:</label> <input id="ticketNum" type="number" name="ticketNum" value="0" /> ``` {{EmbedLiveSample('A_simple_number_input', 600, 40)}} A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute is used, the input is no longer considered valid when empty. > **Note:** Any number is an acceptable value, as long as it is a [valid floating point number](https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number) (that is, not [NaN](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) or [Infinity](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity)). ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each {{HTMLElement("input")}}. This is where **placeholders** come in. A placeholder is a value most commonly used to provide a hint as to the format the input should take `value`. It is displayed inside the edit box when the element's `value` is `""`. Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have an `number` input with the placeholder "`Multiple of 10`". Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ```html <input type="number" placeholder="Multiple of 10" /> ``` {{EmbedLiveSample('Placeholders', 600, 40)}} ### Controlling step size By default, the up and down buttons provided for you to step the number up and down will step the value up and down by 1. You can change this by providing a [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute, which takes as its value a number specifying the step amount. Our above example contains a placeholder saying that the value should be a multiple of 10, so it makes sense to add a `step` value of `10`: ```html <input type="number" placeholder="multiple of 10" step="10" /> ``` {{EmbedLiveSample('Controlling_step_size', 600, 40)}} In this example, you should find that the up and down step arrows will increase and decrease the value by 10 each time, not 1. You can still manually enter a number that's not a multiple of 10, but it will be considered invalid. ### Specifying minimum and maximum values You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of `0`, and a maximum of `100`: ```html <input type="number" placeholder="multiple of 10" step="10" min="0" max="100" /> ``` {{EmbedLiveSample('Specifying_minimum_and_maximum_values', 600, 40)}} In this updated version, you should find that the up and down step buttons will not allow you to go below 0 or above 100. You can still manually enter a number outside these bounds, but it will be considered invalid. ### Allowing decimal values One issue with number inputs is that their step size is 1 by default. If you try to enter a number with a decimal (such as "1.0"), it will be considered invalid. If you want to enter a value that requires decimals, you'll need to reflect this in the `step` value (e.g. `step="0.01"` to allow decimals to two decimal places). Here's a simple example: ```html <input type="number" placeholder="1.0" step="0.01" min="0" max="10" /> ``` {{EmbedLiveSample("Allowing_decimal_values", 600, 40)}} See that this example allows any value between `0.0` and `10.0`, with decimals to two places. For example, "9.52" is valid, but "9.521" is not. ### Controlling input size {{HTMLElement("input")}} elements of type `number` don't support form sizing attributes such as [`size`](/en-US/docs/Web/HTML/Element/input#size). You'll have to resort to [CSS](/en-US/docs/Web/CSS) to change the size of these controls. For example, to adjust the width of the input to be only as wide as is needed to enter a three-digit number, we can change our HTML to include an [`id`](/en-US/docs/Web/HTML/Global_attributes#id) and to shorten our placeholder since the field will be too narrow for the text we have been using so far: ```html <input type="number" placeholder="x10" step="10" min="0" max="100" id="number" /> ``` Then we add some CSS to narrow the width of the element with the `id` selector `#number`: ```css #number { width: 3em; } ``` The result looks like this: {{EmbedLiveSample('Controlling_input_size', 600, 40)}} ### Offering suggested values You can provide a list of default options from which the user can select by specifying the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute, which contains as its value the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of a {{HTMLElement("datalist")}}, which in turn contains one {{HTMLElement("option")}} element per suggested value. Each `option`'s `value` is the corresponding suggested value for the number entry box. ```html <input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers" /> <span class="validity"></span> <datalist id="defaultNumbers"> <option value="10045678"></option> <option value="103421"></option> <option value="11111111"></option> <option value="12345678"></option> <option value="12999922"></option> </datalist> ``` {{EmbedLiveSample("Offering_suggested_values", 600, 40)}} ## Validation We have already mentioned a number of validation features of `number` inputs, but let's review them now: - `<input type="number">` elements automatically invalidate any entry that isn't a number (or empty, unless `required` is specified). - You can use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute to make an empty entry invalid. (In other words, the input _must_ be filled in.) - You can use the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute to constrain valid values to a certain set of steps (e.g., multiples of 10). - You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to constrain valid values to lower and upper bounds. The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons, depending on the `input`'s value: ```html <form> <div> <label for="balloons">Number of balloons to order (multiples of 10):</label> <input id="balloons" type="number" name="balloons" step="10" min="0" max="100" required /> <span class="validity"></span> </div> <div> <input type="submit" /> </div> </form> ``` {{EmbedLiveSample("Validation", 600, 110)}} Try submitting the form with different invalid values entered — e.g., no value; a value below 0 or above 100; a value that is not a multiple of 10; or a non-numerical value — and see how the error messages the browser gives you differ with different ones. The CSS applied to this example is as follows: ```css div { margin-bottom: 10px; } input:invalid + span::after { content: "✖"; padding-left: 5px; } input:valid + span::after { content: "✓"; padding-left: 5px; } ``` Here we use the {{cssxref(":invalid")}} and {{cssxref(":valid")}} pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent {{htmlelement("span")}} element, as a visual indicator of validity. We put it on a separate `<span>` element for added flexibility. Some browsers don't display generated content very effectively on some types of form inputs. (Read, for example, the section on [`<input type="date">` validation](/en-US/docs/Web/HTML/Element/input/date#validation).) > **Warning:** HTML form validation is _not_ a substitute for server-side scripts that ensure that the entered data is in the proper format! > > It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML and submit the data directly to your server. > > If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth). ### Pattern validation `<input type="number">` elements do not support use of the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes (as explained above). ## Examples We've already covered the fact that by default, the increment is `1`, and you can use the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute to allow decimal inputs. Let's take a closer look. In the following example is a form for entering the user's height. It defaults to accepting a height in meters, but you can click the relevant button to change the form to accept feet and inches instead. The input for the height in meters accepts decimals to two places. {{EmbedLiveSample("Examples", 600, 150)}} The HTML looks like this: ```html <form> <div class="metersInputGroup"> <label for="meters">Enter your height — meters:</label> <input id="meters" type="number" name="meters" step="0.01" min="0" placeholder="e.g. 1.78" required /> <span class="validity"></span> </div> <div class="feetInputGroup" style="display: none;"> <span>Enter your height — </span> <label for="feet">feet:</label> <input id="feet" type="number" name="feet" min="0" step="1" /> <span class="validity"></span> <label for="inches">inches:</label> <input id="inches" type="number" name="inches" min="0" max="11" step="1" /> <span class="validity"></span> </div> <div> <input type="button" class="meters" value="Enter height in feet and inches" /> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` You'll see that we are using many of the attributes we've already looked at in the article earlier on. Since we want to accept a meter value in centimeters, we've set the `step` value to `0.01`, so that values like _1.78_ are not seen as invalid. We've also provided a placeholder for that input. We've hidden the feet and inches inputs initially using `style="display: none;"`, so that meters is the default entry type. Now, onto the CSS. This looks very similar to the validation styling we saw before; nothing remarkable here. ```css div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` And finally, the JavaScript: ```js const metersInputGroup = document.querySelector(".metersInputGroup"); const feetInputGroup = document.querySelector(".feetInputGroup"); const metersInput = document.querySelector("#meters"); const feetInput = document.querySelector("#feet"); const inchesInput = document.querySelector("#inches"); const switchBtn = document.querySelector('input[type="button"]'); switchBtn.addEventListener("click", () => { if (switchBtn.getAttribute("class") === "meters") { switchBtn.setAttribute("class", "feet"); switchBtn.value = "Enter height in meters"; metersInputGroup.style.display = "none"; feetInputGroup.style.display = "block"; feetInput.setAttribute("required", ""); inchesInput.setAttribute("required", ""); metersInput.removeAttribute("required"); metersInput.value = ""; } else { switchBtn.setAttribute("class", "meters"); switchBtn.value = "Enter height in feet and inches"; metersInputGroup.style.display = "block"; feetInputGroup.style.display = "none"; feetInput.removeAttribute("required"); inchesInput.removeAttribute("required"); metersInput.setAttribute("required", ""); feetInput.value = ""; inchesInput.value = ""; } }); ``` After declaring a few variables, an event listener is added to the `button` to control the switching mechanism. This is pretty simple, mostly involving changing over the button's `class` and {{HTMLElement("label")}}, and updating the display values of the two sets of inputs when the button is pressed. (Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.) > **Note:** When the user clicks the button, the `required` attribute(s) are removed from the input(s) we are hiding, and empty the `value` attribute(s). This is so the form can be submitted if both input sets aren't filled in. It also ensures that the form won't submit data that the user didn't mean to. > > If you didn't do this, you'd have to fill in both feet/inches **and** meters to submit the form! ## Accessibility concerns The implicit [role](/en-US/docs/Web/Accessibility/ARIA/Roles) for the `<input type="number">` element is [`spinbutton`](/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role). If spinbutton is not an important feature for your form control, consider _not_ using `type="number"`. Instead, use [`inputmode="numeric"`](/en-US/docs/Web/HTML/Global_attributes/inputmode) along with a [`pattern`](/en-US/docs/Web/HTML/Attributes/pattern) attribute that limits the characters to numbers and associated characters. With `<input type="number">`, there is a risk of users accidentally incrementing a number when they're trying to do something else. Additionally, if users try to enter something that's not a number, there's no explicit feedback about what they're doing wrong. Also consider using the [`autocomplete`](/en-US/docs/Web/HTML/Attributes/autocomplete) attribute to help users complete forms more quickly and with fewer chances of errors. For example, to enable autofill on a zip code field, set `autocomplete="postal-code"`. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>A {{jsxref("Number")}} representing a number, or empty</td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>list</code>, <code>value</code>, <code>valueAsNumber</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td> <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/spinbutton_role">spinbutton</a></code> </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML forms guide](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} - [`<input type="tel">`](/en-US/docs/Web/HTML/Element/input/tel) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls) - [Article: Why Gov.UK changed the input type for numbers](https://technology.blog.gov.uk/2020/02/24/why-the-gov-uk-design-system-team-changed-the-input-type-for-numbers/)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/tel/index.md
--- title: <input type="tel"> slug: Web/HTML/Element/input/tel page-type: html-element browser-compat: html.elements.input.type_tel --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`tel`** are used to let the user enter and edit a telephone number. Unlike [`<input type="email">`](/en-US/docs/Web/HTML/Element/input/email) and [`<input type="url">`](/en-US/docs/Web/HTML/Element/input/url), the input value is not automatically validated to a particular format before the form can be submitted, because formats for telephone numbers vary so much around the world. {{EmbedInteractiveExample("pages/tabbed/input-tel.html", "tabbed-standard")}} Despite the fact that inputs of type `tel` are functionally identical to standard `text` inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient. > **Note:** Browsers that don't support type `tel` fall back to being a standard {{HTMLElement("input/text", "text")}} input. ## Value The {{HTMLElement("input")}} element's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string that either represents a telephone number or is an empty string (`""`). ## Additional attributes In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, telephone number inputs support the following attributes. ### list The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum string length (measured in UTF-16 code units) that the user can enter into the telephone number field. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the telephone number field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. ### minlength The minimum string length (measured in UTF-16 code units) that the user can enter into the telephone number field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the telephone number input has no minimum length. The telephone number field will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. ### pattern The `pattern` attribute, when specified, is a regular expression that 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 `'u'` flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. > **Note:** Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See [Pattern validation](#pattern_validation) below for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ({{cssxref("font")}} settings in use). This does _not_ set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ## Non-standard attributes The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can't be helped. ### autocorrect A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: - `on` - : Enable automatic correction of typos, as well as processing of text substitutions if any are configured. - `off` - : Disable automatic correction and text substitutions. ### mozactionhint {{deprecated_inline}} A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field. <strong>Deprecated: Use [`enterkeyhint`](/en-US/docs/Web/HTML/Global_attributes#enterkeyhint) instead.</strong> ## Using tel inputs Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how commonly-entered phone numbers are, it's unfortunate that a "one size fits all" solution for validating phone numbers is not practical. Fortunately, you can consider the requirements of your own site and implement an appropriate level of validation yourself. See [Validation](#validation), below, for details. ### Custom keyboards One of the main advantages of `<input type="tel">` is that it causes mobile browsers to display a special keyboard for entering phone numbers. For example, here's what the keypads look like on a couple of devices. | Firefox for Android | WebKit iOS (Safari/Chrome/Firefox) | | ------------------------------------------------------ | ------------------------------------------------------------ | | ![Firefox for Android screen shot](fx-android-tel.png) | ![Firefox for iOS screenshot](iphone-tel-keyboard-50pct.png) | ### A simple tel input In its most basic form, a tel input can be implemented like this: ```html <label for="telNo">Phone number:</label> <input id="telNo" name="telNo" type="tel" /> ``` {{ EmbedLiveSample('A_simple_tel_input', 600, 40) }} There is nothing magical going on here. When submitted to the server, the above input's data would be represented as, for example, `telNo=+12125553151`. ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each {{HTMLElement("input")}}. This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is `""`. Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have an `tel` input with the placeholder `123-4567-8901`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ```html <input id="telNo" name="telNo" type="tel" placeholder="123-4567-8901" /> ``` {{ EmbedLiveSample('Placeholders', 600, 40) }} ### Controlling the input size You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself. #### Physical input element size The physical size of the input box can be controlled using the [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the `tel` edit box is 20 characters wide: ```html <input id="telNo" name="telNo" type="tel" size="20" /> ``` {{ EmbedLiveSample('Physical_input_element_size', 600, 40) }} #### Element value length The `size` is separate from the length limitation on the entered telephone number. You can specify a minimum length, in characters, for the entered telephone number using the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute; similarly, use [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) to set the maximum length of the entered telephone number. The example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters. ```html <input id="telNo" name="telNo" type="tel" size="20" minlength="9" maxlength="14" /> ``` {{EmbedLiveSample("Element_value_length", 600, 40) }} > **Note:** The above attributes do affect [Validation](#validation) — the above example's inputs will count as invalid if the length of the value is less than 9 characters, or more than 14. Most browser won't even let you enter a value over the max length. ### Providing default options #### Providing a single default using the value attribute As always, you can provide a default value for an `tel` input box by setting its [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute: ```html <input id="telNo" name="telNo" type="tel" value="333-4444-4444" /> ``` {{EmbedLiveSample("Providing_a_single_default_using_the_value_attribute", 600, 40)}} #### Offering suggested values Taking it a step further, you can provide a list of default phone number values from which the user can select. To do this, use the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute. This doesn't limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. This also offers hints to [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete). The `list` attribute specifies the ID of a {{HTMLElement("datalist")}} element, which in turn contains one {{HTMLElement("option")}} element per suggested value; each `option`'s `value` is the corresponding suggested value for the telephone number entry box. ```html <label for="telNo">Phone number: </label> <input id="telNo" name="telNo" type="tel" list="defaultTels" /> <datalist id="defaultTels"> <option value="111-1111-1111"></option> <option value="122-2222-2222"></option> <option value="333-3333-3333"></option> <option value="344-4444-4444"></option> </datalist> ``` {{EmbedLiveSample("Offering_suggested_values", 600, 40)}} With the {{HTMLElement("datalist")}} element and its {{HTMLElement("option")}}s in place, the browser will offer the specified values as potential values for the phone number; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested phone numbers. Then, as the user types, the list is adjusted to show only filtered matching values. Each typed character narrows down the list until the user makes a selection or types a custom value. Here's a screenshot of what that might look like: ![An input box has focus with a blue focus ring. The input has a drop-down menu showing four phone numbers the user can select.](phone-number-with-options.png) ## Validation As we've touched on before, it's quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. So what can we do? Let's consider some options. > **Warning:** HTML form validation is _not_ a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### Making telephone numbers required You can make it so that an empty input is invalid and won't be submitted to the server using the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute. For example, let's use this HTML: ```html <form> <div> <label for="telNo">Enter a telephone number (required): </label> <input id="telNo" name="telNo" type="tel" required /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` And let's include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross: ```css div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; color: #8b0000; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; color: #009000; } ``` The output looks like this: {{EmbedLiveSample("Making_telephone_numbers_required", 700, 70)}} ### Pattern validation If you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute, which takes as its value a {{Glossary("regular expression")}} that entered values have to match. In this example we'll use the same CSS as before, but our HTML is changed to look like this: ```html <form> <div> <label for="telNo"> Enter a telephone number (in the form xxx-xxx-xxxx): </label> <input id="telNo" name="telNo" type="tel" required pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; color: #8b0000; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; color: #009000; } ``` {{EmbedLiveSample("Pattern_validation", 700, 70)}} Notice how the entered value is reported as invalid unless the pattern xxx-xxx-xxxx is matched; for instance, 41-323-421 won't be accepted. Neither will 800-MDN-ROCKS. However, 865-555-6502 will be accepted. This particular pattern is obviously only useful for certain locales — in a real application you'd probably have to vary the pattern used depending on the locale of the user. ## Examples In this example, we present a simple interface with a {{htmlelement("select")}} element that lets the user choose which country they're in, and a set of `<input type="tel">` elements to let them enter each part of their phone number; there is no reason why you can't have multiple `tel` inputs. Each input has a [`placeholder`](/en-US/docs/Web/HTML/Element/input#placeholder) attribute to show a hint to sighted users about what to enter into it, a [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) to enforce a specific number of characters for the desired section, and an [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute to contain a hint to be read out to screen reader users about what to enter into it. ```html <form> <div> <label for="country">Choose your country:</label> <select id="country" name="country"> <option>UK</option> <option selected>US</option> <option>Germany</option> </select> </div> <div> <p>Enter your telephone number:</p> <span class="areaDiv"> <input id="areaNo" name="areaNo" type="tel" required placeholder="Area code" pattern="[0-9]{3}" aria-label="Area code" /> <span class="validity"></span> </span> <span class="number1Div"> <input id="number1" name="number1" type="tel" required placeholder="First part" pattern="[0-9]{3}" aria-label="First part of number" /> <span class="validity"></span> </span> <span class="number2Div"> <input id="number2" name="number2" type="tel" required placeholder="Second part" pattern="[0-9]{4}" aria-label="Second part of number" /> <span class="validity"></span> </span> </div> <div> <button>Submit</button> </div> </form> ``` The JavaScript is relatively simple — it contains an {{domxref("HTMLElement.change_event", "onchange")}} event handler that, when the `<select>` value is changed, updates the `<input>` element's `pattern`, `placeholder`, and `aria-label` to suit the format of telephone numbers in that country/territory. ```js const selectElem = document.querySelector("select"); const inputElems = document.querySelectorAll("input"); selectElem.onchange = () => { for (let i = 0; i < inputElems.length; i++) { inputElems[i].value = ""; } if (selectElem.value === "US") { inputElems[2].parentNode.style.display = "inline"; inputElems[0].placeholder = "Area code"; inputElems[0].pattern = "[0-9]{3}"; inputElems[1].placeholder = "First part"; inputElems[1].pattern = "[0-9]{3}"; inputElems[1].setAttribute("aria-label", "First part of number"); inputElems[2].placeholder = "Second part"; inputElems[2].pattern = "[0-9]{4}"; inputElems[2].setAttribute("aria-label", "Second part of number"); } else if (selectElem.value === "UK") { inputElems[2].parentNode.style.display = "none"; inputElems[0].placeholder = "Area code"; inputElems[0].pattern = "[0-9]{3,6}"; inputElems[1].placeholder = "Local number"; inputElems[1].pattern = "[0-9]{4,8}"; inputElems[1].setAttribute("aria-label", "Local number"); } else if (selectElem.value === "Germany") { inputElems[2].parentNode.style.display = "inline"; inputElems[0].placeholder = "Area code"; inputElems[0].pattern = "[0-9]{3,5}"; inputElems[1].placeholder = "First part"; inputElems[1].pattern = "[0-9]{2,4}"; inputElems[1].setAttribute("aria-label", "First part of number"); inputElems[2].placeholder = "Second part"; inputElems[2].pattern = "[0-9]{4}"; inputElems[2].setAttribute("aria-label", "Second part of number"); } }; ``` The example looks like this: {{EmbedLiveSample('Examples', 600, 140)}} This is an interesting idea, which goes to show a potential solution to the problem of dealing with international phone numbers. You would have to extend the example of course to provide the correct pattern for potentially every country, which would be a lot of work, and there would still be no foolproof guarantee that the users would enter their numbers correctly. It makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server. But this choice is yours to make. ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid + span::after { position: absolute; content: "✖"; padding-left: 5px; color: #8b0000; } input:valid + span::after { position: absolute; content: "✓"; padding-left: 5px; color: #009000; } ``` ## Technical Summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing a telephone number, or empty </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#maxlength"><code>maxlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#minlength"><code>minlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#pattern"><code>pattern</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#size"><code>size</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>list</code>, <code>selectionStart</code>, <code>selectionEnd</code>, <code>selectionDirection</code>, and <code>value</code> </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}, {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td>with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code></td> <td>with <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role">combobox</a></code></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML forms guide](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} - [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text) - [`<input type="email">`](/en-US/docs/Web/HTML/Element/input/email) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/image/index.md
--- title: <input type="image"> slug: Web/HTML/Element/input/image page-type: html-element browser-compat: html.elements.input.type_image --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`image`** are used to create graphical submit buttons, i.e. submit buttons that take the form of an image rather than text. {{EmbedInteractiveExample("pages/tabbed/input-image.html", "tabbed-standard")}} ## Value `<input type="image">` elements do not accept `value` attributes. The path to the image to be displayed is specified in the `src` attribute. ## Additional attributes In addition to the attributes shared by all {{HTMLElement("input")}} elements, `image` button inputs support the following attributes. ### alt The `alt` attribute provides an alternate string to use as the button's label if the image cannot be shown (due to error, a {{Glossary("user agent")}} that cannot or is configured not to show images, or if the user is using a screen reading device). If provided, it must be a non-empty string appropriate as a label for the button. For example, if you have a graphical button that shows an image with an icon and/or image text "Login Now", you should also set the `alt` attribute to something like `Login Now`. > **Note:** While the `alt` attribute is technically optional, you should always include one to maximize the usability of your content. Functionally, the `alt` attribute of the `<input type="image">` element works just like the [`alt`](/en-US/docs/Web/HTML/Element/img#alt) attribute on {{HTMLElement("img")}} elements. ### formaction A string indicating the URL to which to submit the data. This takes precedence over the [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute on the {{HTMLElement("form")}} element that owns the {{HTMLElement("input")}}. This attribute is also available on [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit) and {{HTMLElement("button")}} elements. ### formenctype A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values: - `application/x-www-form-urlencoded` - : This, the default value, sends the form data as a string after [URL encoding](https://en.wikipedia.org/wiki/URL_encoding) the text using an algorithm such as {{jsxref("encodeURI", "encodeURI()")}}. - `multipart/form-data` - : Uses the {{domxref("FormData")}} API to manage the data, allowing for files to be submitted to the server. You _must_ use this encoding type if your form includes any {{HTMLElement("input")}} elements of [`type`](/en-US/docs/Web/HTML/Element/input#type) `file` ([`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file)). - `text/plain` - : Plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted. If specified, the value of the `formenctype` attribute overrides the owning form's [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute. This attribute is also available on [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit) and {{HTMLElement("button")}} elements. ### formmethod A string indicating the HTTP method to use when submitting the form's data; this value overrides any [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute given on the owning form. Permitted values are: - `get` - : A URL is constructed by starting with the URL given by the `formaction` or [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by `formenctype` or the form's [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) attribute. This URL is then sent to the server using an HTTP {{HTTPMethod("get")}} request. This method works well for simple forms that contain only {{Glossary("ASCII")}} characters and have no side effects. This is the default value. - `post` - : The form's data is included in the body of the request that is sent to the URL given by the `formaction` or [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute using an HTTP {{HTTPMethod("post")}} request. This method supports complex data and file attachments. - `dialog` - : This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all. This attribute is also available on [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit) and {{HTMLElement("button")}} elements. ### formnovalidate A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute on the element's owning form. This attribute is also available on [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit) and {{HTMLElement("button")}} elements. ### formtarget A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a **browsing context** (that is, a tab, window, or {{HTMLElement("iframe")}}. A value specified here overrides any target given by the [`target`](/en-US/docs/Web/HTML/Element/form#target) attribute on the {{HTMLElement("form")}} that owns this input. In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: - `_self` - : Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. - `_blank` - : Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the {{Glossary("user agent")}}. - `_parent` - : Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as `_self`. - `_top` - : Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as `_self`. This attribute is also available on [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit) and {{HTMLElement("button")}} elements. ### height A number specifying the height, in CSS pixels, at which to draw the image specified by the `src` attribute. ### src A string specifying the URL of the image file to display to represent the graphical submit button. When the user interacts with the image, the input is handled like any other button input. ### width A number indicating the width at which to draw the image, in CSS pixels. ## Obsolete attributes The following attribute was defined by HTML 4 for `image` inputs, but was not implemented by all browsers and has since been deprecated. ### usemap If `usemap` is specified, it must be the name of an image map element, {{HTMLElement("map")}}, that defines an image map to use with the image. This usage is obsolete; you should switch to using the {{HTMLElement("img")}} element when you want to use image maps. ## Using image inputs The `<input type="image">` element is a [replaced element](/en-US/docs/Web/CSS/Replaced_element) (an element whose content isn't generated or directly managed by the CSS layer), behaving in much the same way as a regular {{htmlelement("img")}} element, but with the capabilities of a [submit button](/en-US/docs/Web/HTML/Element/input/submit). ### Essential image input features Let's look at a basic example that includes all the essential features you'd need to use (These work exactly the same as they do on the `<img>` element.): ```html <input id="image" type="image" width="100" height="30" alt="Login" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" /> ``` {{ EmbedLiveSample('Essential_image_input_features', 600, 50) }} - The [`src`](/en-US/docs/Web/HTML/Element/input#src) attribute is used to specify the path to the image you want to display in the button. - The [`alt`](/en-US/docs/Web/HTML/Element/input#alt) attribute provides alt text for the image, so screen reader users can get a better idea of what the button is used for. It will also display if the image can't be shown for any reason (for example if the path is misspelled). If possible, use text which matches the label you'd use if you were using a standard submit button. - The [`width`](/en-US/docs/Web/HTML/Element/input#width) and [`height`](/en-US/docs/Web/HTML/Element/input#height) attributes are used to specify the width and height the image should be shown at, in pixels. The button is the same size as the image; if you need the button's hit area to be bigger than the image, you will need to use CSS (e.g. {{cssxref("padding")}}). Also, if you specify only one dimension, the other is automatically adjusted so that the image maintains its original aspect ratio. ### Overriding default form behaviors `<input type="image">` elements — like regular [submit buttons](/en-US/docs/Web/HTML/Element/input/submit) — can accept a number of attributes that override the default form behavior: - `formaction` - : The URI of a program that processes the information submitted by the input element; overrides the [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute of the element's form owner. - `formenctype` - : Specifies the type of content that is used to submit the form to the server. Possible values are: - `application/x-www-form-urlencoded`: The default value if the attribute is not specified. - `text/plain`. If this attribute is specified, it overrides the [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) attribute of the element's form owner. - `formmethod` - : Specifies the HTTP method that the browser uses to submit the form. Possible values are: - `post`: The data from the form is included in the body of the form and is sent to the server. - `get`: The data from the form is appended to the **`form`** attribute URI, with a '?' as a separator, and the resulting URI is sent to the server. Use this method when the form has no side effects and contains only ASCII characters. If specified, this attribute overrides the [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute of the element's form owner. - `formnovalidate` - : A Boolean attribute specifying that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute of the element's form owner. - `formtarget` - : A name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a _browsing context_ (for example, tab, window, or inline frame). If this attribute is specified, it overrides the [`target`](/en-US/docs/Web/HTML/Element/form#target) attribute of the element's form owner. The following keywords have special meanings: - \_`self`: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified. - `_blank`: Load the response into a new unnamed browsing context. - `_parent`: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as `_self`. - `_top`: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same as `_self`. ### Using the x and y data points When you submit a form using a button created with `<input type="image">`, two extra data points are submitted to the server automatically by the browser — `x` and `y`. You can see this in action in our [X Y coordinates example](https://mdn.github.io/learning-area/html/forms/image-type-example/xy-coordinates-example.html). When you click on the image to submit the form, you'll see the data appended to the URL as parameters, for example `?x=52&y=55`. If the image input has a [`name`](/en-US/docs/Web/HTML/Element/input#name) attribute, then keep in mind that the specified name is prefixed on every attribute, so if the `name` is `position`, then the returned coordinates would be formatted in the URL as `?position.x=52&position.y=55`. This, of course, applies to all other attributes as well. These are the X and Y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image and the default in case submission happens without a click on the image. These can be used when the position the image was clicked on is significant, for example you might have a map that when clicked, sends the coordinates that were clicked to the server. The server-side code then works out what location was clicked on, and returns information about places nearby. In our above example, we could write server-side code that works out what color was clicked on by the coordinates submitted, and keeps a tally of the favorite colors people voted for. ### Adjusting the image's position and scaling algorithm You can use the {{cssxref("object-position")}} property to adjust the positioning of the image within the `<input>` element's frame, and the {{cssxref("object-fit")}} property to control how the image's size is adjusted to fit within the frame. This allows you to specify a frame for the image using the `width` and `height` attributes to set aside space in the layout, then adjust where within that space the image is located and how (or if) it is scaled to occupy that space. ## Examples ### A login form The following example shows the same button as before, but included in the context of a typical login form. {{ EmbedLiveSample('A_login_form', 600, 170) }} #### HTML ```html <form> <p>Login to your account</p> <div> <label for="userId">User ID</label> <input type="text" id="userId" name="userId" /> </div> <div> <label for="pwd">Password</label> <input type="password" id="pwd" name="pwd" /> </div> <div> <input id="image" type="image" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" alt="Login" width="100" /> </div> </form> ``` #### CSS And now some simple CSS to make the basic elements sit more neatly: ```css div { margin-bottom: 10px; } label { display: inline-block; width: 70px; text-align: right; padding-right: 10px; } ``` ### Adjusting the image position and scaling In this example, we adapt the previous example to set aside more space for the image and then adjust the actual image's size and positioning using {{cssxref("object-fit")}} and {{cssxref("object-position")}}. {{EmbedLiveSample("Adjusting_the_image_position_and_scaling", 600, 300)}} #### HTML ```html <form> <p>Login to your account</p> <div> <label for="userId">User ID</label> <input type="text" id="userId" name="userId" /> </div> <div> <label for="pwd">Password</label> <input type="password" id="pwd" name="pwd" /> </div> <div> <input id="image" type="image" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" alt="Login" width="200" height="100" /> </div> </form> ``` #### CSS ```css div { margin-bottom: 10px; } label { display: inline-block; width: 70px; text-align: right; padding-right: 10px; } #image { object-position: right top; object-fit: contain; background-color: #ddd; } ``` Here, `object-position` is configured to draw the image in the top-right corner of the element, while `object-fit` is set to `contain`, which indicates that the image should be drawn at the largest size that will fit within the element's box without altering its aspect ratio. Note the visible grey background of the element still visible in the area not covered by the image. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>None — the <code>value</code> attribute should not be specified.</td> </tr> <tr> <td><strong>Events</strong></td> <td>None.</td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#alt"><code>alt</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#src"><code>src</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#width"><code>width</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#height"><code>height</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#formaction"><code>formaction</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#formenctype"><code>formenctype</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#formmethod"><code>formmethod</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#formmethod"><code>formnovalidate</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#formtarget"><code>formtarget</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td>None.</td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td>None.</td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role"><code>button</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it. - The HTML {{HTMLElement("img")}} element - Positioning and sizing the image within the `<input>` element's frame: {{cssxref("object-position")}} and {{cssxref("object-fit")}} - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/url/index.md
--- title: <input type="url"> slug: Web/HTML/Element/input/url page-type: html-element browser-compat: html.elements.input.type_url --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`url`** are used to let the user enter and edit a URL. {{EmbedInteractiveExample("pages/tabbed/input-url.html", "tabbed-shorter")}} The input value is automatically validated to ensure that it's either empty or a properly-formatted URL before the form can be submitted. The {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid URL or not. On browsers that don't support inputs of type `url`, a `url` input falls back to being a standard {{HTMLElement("input/text", "text")}} input. ## Value The {{HTMLElement("input")}} element's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string which is automatically validated as conforming to URL syntax. More specifically, there are two possible value formats that will pass validation: 1. An empty string ("") indicating that the user did not enter a value or that the value was removed. 2. A single properly-formed absolute URL. This doesn't necessarily mean the URL address exists, but it is at least formatted correctly. In simple terms, this means `urlscheme://restofurl`. See [Validation](#validation) for details on how URLs are validated to ensure that they're formatted properly. ## Additional attributes In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, `url` inputs support the following attributes. ### list The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### maxlength The maximum string length (measured in UTF-16 code units) that the user can enter into the `url` input. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the `url` input has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/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. ### minlength The minimum string length (measured in UTF-16 code units) that the user can enter into the `url` input. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the `url` input has no minimum length. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. ### pattern The `pattern` attribute, when specified, is a regular expression that 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 `'u'` flag is specified when compiling the regular expression so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. > **Note:** Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. See the section [Pattern validation](#pattern_validation) for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ({{cssxref("font")}} settings in use). This does _not_ set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ### spellcheck `spellcheck` is a global attribute which is used to indicate whether to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of `spellcheck` on {{HTMLElement("input")}} elements. The permitted values for `spellcheck` are: - `false` - : Disable spell checking for this element. - `true` - : Enable spell checking for this element. - "" (empty string) or no value - : Follow the element's default behavior for spell checking. This may be based upon a parent's `spellcheck` setting or other factors. An input field can have spell checking enabled if it doesn't have the [readonly](#readonly) attribute set and is not disabled. The value returned by reading `spellcheck` may not reflect the actual state of spell checking within a control, if the {{Glossary("user agent", "user agent's")}} preferences override the setting. ## Non-standard attributes The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. ### autocorrect A Safari extension, the `autocorrect` attribute is a string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are: - `on` - : Enable automatic correction of typos, as well as processing of text substitutions if any are configured. - `off` - : Disable automatic correction and text substitutions. ### mozactionhint {{deprecated_inline}} A Mozilla extension, which provides a hint as to what sort of action will be taken if the user presses the <kbd>Enter</kbd> or <kbd>Return</kbd> key while editing the field. <strong>Deprecated: Use [`enterkeyhint`](/en-US/docs/Web/HTML/Global_attributes#enterkeyhint) instead.</strong> ## Using URL inputs When you create a URL input with the proper `type` value, `url`, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mistypes their website's address, or provides an invalid one. It's important, however, to note that this is not enough to ensure that the specified text is a URL which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be a URL. > **Note:** A user can tinker with your HTML behind the scenes, so your site _must not_ use this validation for any security purposes. You _must_ verify the URL on the server-side of any transaction in which the provided text may have any security implications of any kind. ### A simple URL input Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. In its most basic form, a URL input can be implemented like this: ```html <input id="myURL" name="myURL" type="url" /> ``` {{ EmbedLiveSample('A_simple_URL_input', 600, 40) }} Notice that it's considered valid when empty and when a single validly-formatted URL address is entered, but is otherwise not considered valid. By adding the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute, only properly-formed URLs are allowed; the input is no longer considered valid when empty. There is nothing magical going on here. Submitting this form would cause the following data to be sent to the server: `myURL=http%3A%2F%2Fwww.example.com`. Note how characters are escaped as necessary. ### Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each {{HTMLElement("input")}}. This is where **placeholders** come in. A placeholder is a value that demonstrates the form the `value` should take by presenting an example of a valid value, which is displayed inside the edit box when the element's `value` is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears. Here, we have a `url` input with the placeholder `http://www.example.com`. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field. ```html <input id="myURL" name="myURL" type="url" placeholder="http://www.example.com" /> ``` {{ EmbedLiveSample('Placeholders', 600, 40) }} ### Controlling the input size You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself. #### Physical input element size The physical size of the input box can be controlled using the [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the `url` edit box is 30 characters wide: ```html <input id="myURL" name="myURL" type="url" size="30" /> ``` {{ EmbedLiveSample('Physical_input_element_size', 600, 40) }} #### Element value length The `size` is separate from the length limitation on the entered URL itself. You can specify a minimum length, in characters, for the entered URL using the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) attribute; similarly, use [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) to set the maximum length of the entered URL. If `maxLength` exceeds `size`, the input box's contents will scroll as needed to show the current selection or insertion point as the content is manipulated. The example below creates a 30-character wide URL address entry box, requiring that the contents be no shorter than 10 characters and no longer than 80 characters. ```html <input id="myURL" name="myURL" type="url" size="30" minlength="10" maxlength="80" /> ``` {{EmbedLiveSample("Element_value_length", 600, 40) }} > **Note:** These attributes also affect validation; a value shorter or longer than the specified minimum/maximum lengths will be classified as invalid; in addition most browsers will refuse to let the user enter a value longer than the specified maximum length. ### Providing default options #### Providing a single default using the value attribute As always, you can provide a default value for a `url` input box by setting its [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute: ```html <input id="myURL" name="myURL" type="url" value="http://www.example.com" /> ``` {{EmbedLiveSample("Providing_a_single_default_using_the_value_attribute", 600, 40)}} #### Offering suggested values Taking it a step further, you can provide a list of default options from which the user can select by specifying the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute. This doesn't limit the user to those options, but does allow them to select commonly-used URLs more quickly. This also offers hints to [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete). The `list` attribute specifies the ID of a {{HTMLElement("datalist")}}, which in turn contains one {{HTMLElement("option")}} element per suggested value; each `option`'s `value` is the corresponding suggested value for the URL entry box. ```html <input id="myURL" name="myURL" type="url" list="defaultURLs" /> <datalist id="defaultURLs"> <option value="https://developer.mozilla.org/"></option> <option value="http://www.google.com/"></option> <option value="http://www.microsoft.com/"></option> <option value="https://www.mozilla.org/"></option> <option value="http://w3.org/"></option> </datalist> ``` {{EmbedLiveSample("Offering_suggested_values", 600, 40)}} With the {{HTMLElement("datalist")}} element and its {{HTMLElement("option")}}s in place, the browser will offer the specified values as potential values for the URL; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested URLs. Then, as the user types, the list is adjusted to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value. #### Using labels for suggested values You can opt to include the [`label`](/en-US/docs/Web/HTML/Element/option#label) attribute on one or all of your `<option>` elements to provide textual labels. Some browsers may display only the labels, while others may display both the label and the URL. ```html <input id="myURL" name="myURL" type="url" list="defaultURLs" /> <datalist id="defaultURLs"> <option value="https://developer.mozilla.org/" label="MDN Web Docs"></option> <option value="http://www.google.com/" label="Google"></option> <option value="http://www.microsoft.com/" label="Microsoft"></option> <option value="https://www.mozilla.org/" label="Mozilla"></option> <option value="http://w3.org/" label="W3C"></option> </datalist> ``` {{EmbedLiveSample("Using_labels_for_suggested_values", 600, 40)}} ## Validation There are two levels of content validation available for `url` inputs. First, there's the standard level of validation offered to all {{HTMLElement("input")}}s, which automatically ensures that the contents meet the requirements to be a valid URL. But there's also the option to add additional filtering to ensure that your own specialized needs are met, if you have any. > **Warning:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. ### Basic validation Browsers that support the `url` input type automatically provide validation to ensure that only text that matches the standard format for URLs is entered into the input box. The syntax of a URL is fairly intricate. It's defined by WHATWG's [URL Living Standard](https://url.spec.whatwg.org/) and is described for newcomers in our article [What is a URL?](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL) ### Making a URL required As mentioned earlier, to make a URL entry required before the form can be submitted (you can't leave the field blank), you just need to include the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute on the input. ```html <form> <input id="myURL" name="myURL" type="url" required /> <button>Submit</button> </form> ``` {{EmbedLiveSample("Making_a_URL_required", 600, 40)}} Try submitting the above form with no value entered to see what happens. ### Pattern validation If you need the entered URL to be restricted further than just "any string that looks like a URL," you can use the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute to specify a {{Glossary("regular expression")}} the value must match for the value to be valid. For example, let's say you're building a support page for employees of Myco, Inc. which will let them contact their IT department for help if one of their pages has a problem. In our simplified form, the user needs to enter the URL of the page that has a problem, and a message describing what is wrong. But we want the URL to only successfully validate if the entered URL is in a Myco domain. Since inputs of type `url` validate against both the standard URL validation _and_ the specified [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern), you can implement this easily. Let's see how: ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` ```html <form> <div> <label for="myURL">Enter the problem website address:</label> <input id="myURL" name="myURL" type="url" required pattern=".*\.myco\..*" title="The URL must be in a Myco domain" /> <span class="validity"></span> </div> <div> <label for="myComment">What is the problem?</label> <input id="myComment" name="myComment" type="text" required /> <span class="validity"></span> </div> <div> <button>Submit</button> </div> </form> ``` {{EmbedLiveSample("Pattern_validation", 700, 150)}} First of all, the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute is specified, making it mandatory that a valid URL be provided. Second, in the `url` input we set `pattern` to `".*\.myco\..*"`. This simple regular expression requests a string that has any number of characters, followed by a dot, followed by "myco", followed by a dot, followed by any number of characters. And because the browser runs both the standard URL filter _and_ our custom pattern against the specified text, we wind up with a validation which says "make sure this is a valid URL, and also in a Myco domain." This isn't perfect, but it is good enough for this simple demo's requirements. It's advisable to use the [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute along with `pattern`. If you do, the `title` _must_ describe the pattern; it should explain what format the data should take on, rather than any other information. That's because the `title` may be displayed or spoken as part of a validation error message. For example, the browser might present the message "The entered text doesn't match the required pattern." followed by your specified `title`. If your `title` is something like "URL", the result would be the message "The entered text doesn't match the required pattern. URL", which is not a good user experience. That's why, instead, we specify the string "The URL must be in a myco domain". By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. The URL should be in a myco domain." > **Note:** If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem. ## Examples There's not much else to say about `url` type inputs; check the [Pattern validation](#pattern_validation) and [Using URL inputs](#using_url_inputs) sections for numerous examples. You can also find our [pattern validation example on GitHub](https://github.com/mdn/learning-area/blob/main/html/forms/url-example/index.html) (see it [running live also](https://mdn.github.io/learning-area/html/forms/url-example/)). ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>A string representing a URL, or empty</td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported Common Attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#maxlength"><code>maxlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#minlength"><code>minlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#pattern"><code>pattern</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#required"><code>required</code></a> and <a href="/en-US/docs/Web/HTML/Element/input#size"><code>size</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>list</code>, <code>value</code>, <code>selectionEnd</code>, <code>selectionDirection</code> </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}} and {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}}. </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td>with no <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></code></td> <td>with <code>list</code> attribute: <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role">combobox</a></code></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML forms guide](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} - [`<input type="tel">`](/en-US/docs/Web/HTML/Element/input/tel) - [`<input type="email">`](/en-US/docs/Web/HTML/Element/input/email) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/month/index.md
--- title: <input type="month"> slug: Web/HTML/Element/input/month page-type: html-element browser-compat: html.elements.input.type_month --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`month`** create input fields that let the user enter a month and year allowing a month and year to be easily entered. The value is a string whose value is in the format "`YYYY-MM`", where `YYYY` is the four-digit year and `MM` is the month number. {{EmbedInteractiveExample("pages/tabbed/input-month.html", "tabbed-shorter")}} The control's UI varies in general from browser to browser; at the moment support is patchy, with only Chrome/Opera and Edge on desktop — and most modern mobile browser versions — having usable implementations. In browsers that don't support `month` inputs, the control degrades gracefully to a simple [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text), although there may be automatic validation of the entered text to ensure it's formatted as expected. For those of you using a browser that doesn't support `month`, the screenshot below shows what it looks like in Chrome and Opera. Clicking the down arrow on the right-hand side brings up a date picker that lets you select the month and year. ![Month control on Chrome browser](month-control-chrome.png) The Microsoft Edge `month` control looks like this: ![Month control on Edge browser](month-control-edge.png) ## Value A string representing the value of the month and year entered into the input, in the form YYYY-MM (four or more digit year, then a hyphen ("`-`"), followed by the two-digit month). The format of the month string used by this input type is described in [Month strings](/en-US/docs/Web/HTML/Date_and_time_formats#month_strings). ### Setting a default value You can set a default value for the input control by including a month and year inside the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute, like so: ```html <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" value="2001-06" /> ``` {{EmbedLiveSample('Setting_a_default_value', 600, 60)}} One thing to note is that the displayed date format differs from the actual `value`; most {{Glossary("user agent", "user agents")}} display the month and year in a locale-appropriate form, based on the set locale of the user's operating system, whereas the date `value` is always formatted `yyyy-MM`. When the above value is submitted to the server, for example, it will look like `bday-month=1978-06`. ### Setting the value using JavaScript You can also get and set the date value in JavaScript using the {{domxref("HTMLInputElement.value")}} property, for example: ```html <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" /> ``` ```js const monthControl = document.querySelector('input[type="month"]'); monthControl.value = "2001-06"; ``` {{EmbedLiveSample("Setting_the_value_using_JavaScript", 600, 60)}} ## Additional attributes In addition to the attributes common to {{HTMLElement("input")}} elements, month inputs offer the following attributes. ### list The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### max The latest year and month, in the string format discussed in the [Value](#value) section above, to accept. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element exceeds this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `max` attribute isn't a valid string in "`yyyy-MM`" format, then the element has no maximum value. This value must specify a year-month pairing later than or equal to the one specified by the `min` attribute. ### min The earliest year and month to accept, in the same "`yyyy-MM`" format described above. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) of the element is less than this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If a value is specified for `min` that isn't a valid year and month string, the input has no minimum value. This value must be a year-month pairing which is earlier than or equal to the one specified by the `max` attribute. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed from JavaScript code that directly sets the value of the {{domxref("HTMLInputElement.value")}} property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `month` inputs, the value of `step` is given in months, with a scaling factor of 1 (since the underlying numeric value is also in months). The default value of `step` is 1 month. ## Using month inputs Date-related inputs (including `month`) sound convenient at first glance; they promise an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user's locale. However, there are issues with `<input type="month">` because at this time, many major browsers don't yet support it. We'll look at basic and more complex uses of `<input type="month">`, then offer advice on mitigating the browser support issue in the section [Handling browser support](#handling_browser_support)). ### Basic uses of month The simplest use of `<input type="month">` involves a basic {{HTMLElement("input")}} and {{htmlelement("label")}} element combination, as seen below: ```html <form> <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" /> </form> ``` {{EmbedLiveSample('Basic_uses_of_month', 600, 40)}} ### Setting maximum and minimum dates You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to restrict the range of dates that the user can choose. In the following example we specify a minimum month of `1900-01` and a maximum month of `2013-12`: ```html <form> <label for="bday-month">What month were you born in?</label> <input id="bday-month" type="month" name="bday-month" min="1900-01" max="2013-12" /> </form> ``` {{EmbedLiveSample('Setting_maximum_and_minimum_dates', 600, 40)}} The result here is that: - Only months between in January 1900 and December 2013 can be selected; months outside that range can't be scrolled to in the control. - Depending on what browser you are using, you might find that months outside the specified range might not be selectable in the month picker (e.g. Edge), or invalid (see [Validation](#validation)) but still available (e.g. Chrome). ### Controlling input size `<input type="month">` doesn't support form sizing attributes such as [`size`](/en-US/docs/Web/HTML/Element/input#size). You'll have to resort to [CSS](/en-US/docs/Web/CSS) for sizing needs. ## Validation By default, `<input type="month">` does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date — which is helpful — but you can still submit the form with the `month` input empty, or enter an invalid date (e.g. the 32nd of April). To help avoid this, you can use [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) to restrict the available dates (see [Setting maximum and minimum dates](#setting_maximum_and_minimum_dates)), and in addition use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field. Let's look at an example; here we've set minimum and maximum dates, and also made the field required: ```html <form> <div> <label for="month"> What month would you like to visit (June to Sept.)? </label> <input id="month" type="month" name="month" min="2022-06" max="2022-09" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try to submit the form without both the month and year specified (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: {{ EmbedLiveSample('Validation', 600, 120) }} Here's a screenshot for those of you who aren't using a supporting browser: ![Month required prompt on Chrome browser](month-required.png) Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether the current value is valid. We had to put the icons on a {{htmlelement("span")}} next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ```css div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` > **Warning:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format. > It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. > It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. > If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). ## Handling browser support As mentioned above, the major problem with using date inputs at the time of writing is that many major browsers don't yet implement them all; only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the `month` picker on Chrome for Android looks like this: ![Month picker on Chrome for Android](month-android.png) Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the more serious of the two. As mentioned earlier, with a `month` input the actual value is always normalized to the format `yyyy-mm`. On the other hand, in its default configuration, a `text` input has no idea what format the date should be in, and this is an issue because of the number of different ways in which people write dates. For example: - `mmyyyy` (072022) - `mm/yyyy` (07/2022) - `mm-yyyy` (07-2022) - `yyyy-mm` (2022-07) - `Month yyyy` (July 2022) - and so forth… One way around this is to put a [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute on your `month` input. Even though the `month` input doesn't use it, if the browser falls back to treating it like a `text` input, the pattern will be used. For example, try viewing the following demo in a browser that doesn't support `month` inputs: ```html <form> <div> <label for="month"> What month would you like to visit (June to Sept.)? </label> <input id="month" type="month" name="month" min="2022-06" max="2022-09" required pattern="[0-9]{4}-[0-9]{2}" /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` {{ EmbedLiveSample('Handling_browser_support', 600, 100) }} If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern `nnnn-nn`, where `n` is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates (such as `0000-42`), or incorrectly formatted dates that follow the pattern. There's also the problem that the user won't necessarily know which of the many date formats is expected. We have work left to do. ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` The best way to deal with dates in forms in a cross-browser way (until all major browsers have supported them for a while) is to get the user to enter the month and year in separate controls ({{htmlelement("select")}} elements being popular; see below for an implementation), or use JavaScript libraries such as the [jQuery date picker](https://jqueryui.com/datepicker/) plugin. ## Examples In this example, we create two sets of UI elements, each designed to let the user select a month and year. The first is a native `month` input, and the other is a pair of {{HTMLElement("select")}} elements that allow choosing a month and year independently, for compatibility with browsers that don't yet support `<input type="month">`. {{EmbedLiveSample('Examples', 600, 140)}} ### HTML The form that requests the month and year looks like this: ```html <form> <div class="nativeDatePicker"> <label for="month-visit">What month would you like to visit us?</label> <input type="month" id="month-visit" name="month-visit" /> <span class="validity"></span> </div> <p class="fallbackLabel">What month would you like to visit us?</p> <div class="fallbackDatePicker"> <div> <span> <label for="month">Month:</label> <select id="month" name="month"> <option selected>January</option> <option>February</option> <option>March</option> <option>April</option> <option>May</option> <option>June</option> <option>July</option> <option>August</option> <option>September</option> <option>October</option> <option>November</option> <option>December</option> </select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"></select> </span> </div> </div> </form> ``` The {{HTMLElement("div")}} with the ID `nativeDatePicker` uses the `month` input type to request the month and year, while the `<div>` with the ID `fallbackDatePicker` instead uses a pair of `<select>` elements. The first requests the month, and the second the year. The `<select>` for choosing the month is hardcoded with the names of the months, as they don't change (leaving localization out of things). The list of available year values is dynamically generated depending on the current year (see the code comments below for detailed explanations of how these functions work). ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` ### JavaScript The JavaScript code that handles selecting which approach to use and to set up the list of years to include in the non-native year `<select>` follows. The part of the example that may be of most interest is the feature detection code. In order to detect whether the browser supports `<input type="month">`, we create a new {{htmlelement("input")}} element, try setting its `type` to `month`, then immediately check what its type is set to. Browsers that don't support type `month` will return `text`, since that's What month falls back to when not supported. If `<input type="month">` is not supported, we hide the native picker and show the fallback picker UI instead. ```js // Get UI elements const nativePicker = document.querySelector(".nativeDatePicker"); const fallbackPicker = document.querySelector(".fallbackDatePicker"); const fallbackLabel = document.querySelector(".fallbackLabel"); const yearSelect = document.querySelector("#year"); const monthSelect = document.querySelector("#month"); // Hide fallback initially fallbackPicker.style.display = "none"; fallbackLabel.style.display = "none"; // Test whether a new date input falls back to a text input or not const test = document.createElement("input"); try { test.type = "month"; } catch (e) { console.log(e.description); } // If it does, run the code inside the if () {} block if (test.type === "text") { // Hide the native picker and show the fallback nativePicker.style.display = "none"; fallbackPicker.style.display = "block"; fallbackLabel.style.display = "block"; // Populate the years dynamically // (the months are always the same, therefore hardcoded) populateYears(); } function populateYears() { // Get the current year as a number const date = new Date(); const year = date.getFullYear(); // Make this year, and the 100 years before it available in the year <select> for (let i = 0; i <= 100; i++) { const option = document.createElement("option"); option.textContent = year - i; yearSelect.appendChild(option); } } ``` > **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! > You'll need to take this into consideration when developing production apps. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing a month and year, or empty. </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#step"><code>step</code></a>. </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}. </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}} - [Date and time formats used in HTML](/en-US/docs/Web/HTML/Date_and_time_formats) - [Date and Time picker tutorial](/en-US/docs/Learn/Forms/Basic_native_form_controls#date_and_time_picker) - [`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local), [`<input type="date">`](/en-US/docs/Web/HTML/Element/input/date), [`<input type="time">`](/en-US/docs/Web/HTML/Element/input/time), and [`<input type="week">`](/en-US/docs/Web/HTML/Element/input/week) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/password/index.md
--- title: <input type="password"> slug: Web/HTML/Element/input/password page-type: html-element browser-compat: html.elements.input.type_password --- {{HTMLSidebar}} `<input>` elements of type **`password`** provide a way for the user to securely enter a password. The element is presented as a one-line plain text editor control in which the text is obscured so that it cannot be read, usually by replacing each character with a symbol such as the asterisk ("\*") or a dot ("•"). This character will vary depending on the {{Glossary("user agent")}} and operating system. {{EmbedInteractiveExample("pages/tabbed/input-password.html", "tabbed-standard")}} The precise behavior of the entry process may vary from browser to browser. Some browsers display the typed character for a moment before obscuring it, while others allow the user to toggle the display of plain-text on and off. Both approaches help a user check that they entered the intended password, which can be particularly difficult on mobile devices. > **Note:** Any forms involving sensitive information like passwords (such as login forms) should be served over HTTPS. > Many browsers now implement mechanisms to warn against insecure login forms; see [Insecure passwords](/en-US/docs/Web/Security/Insecure_passwords). ## Value The [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string whose value is the current contents of the text editing control being used to enter the password. If the user hasn't entered anything yet, this value is an empty string (`""`). If the [`required`](/en-US/docs/Web/HTML/Element/input#required) property is specified, then the password edit box must contain a value other than an empty string to be valid. If the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute is specified, the content of a `password` control is only considered valid if the value passes validation; see [Validation](#validation) for more information. > **Note:** The line feed (U+000A) and carriage return (U+000D) characters are not permitted in a `password` value. When setting the value of a password control, line feed and carriage return characters are stripped out of the value. ## Additional attributes In addition to the attributes that operate on all {{HTMLElement("input")}} elements regardless of their type, password field inputs support the following attributes. ### maxlength The maximum string length (measured in UTF-16 code units) that the user can enter into the password field. This must be an integer value of 0 or higher. If no `maxlength` is specified, or an invalid value is specified, the password field has no maximum length. This value must also be greater than or equal to the value of `minlength`. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is greater than `maxlength` UTF-16 code units long. ### minlength The minimum string length (measured in UTF-16 code units) that the user can enter into the password entry field. This must be a non-negative integer value smaller than or equal to the value specified by `maxlength`. If no `minlength` is specified, or an invalid value is specified, the password input has no minimum length. The input will fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation) if the length of the text entered into the field is fewer than `minlength` UTF-16 code units long. ### pattern The `pattern` attribute, when specified, is a regular expression that 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 `'u'` flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as {{Glossary("ASCII")}}. No forward slashes should be specified around the pattern text. If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. > **Note:** Use the [`title`](/en-US/docs/Web/HTML/Element/input#title) attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. Use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users. With a pattern, you can mandate case rules, require the use of some number of digits and/or punctuation characters, and so forth. See the section [Validation](#validation) for details and an example. ### placeholder The `placeholder` attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text _must not_ include carriage returns or line feeds. If the control's content has one directionality ({{Glossary("LTR")}} or {{Glossary("RTL")}}) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see [How to use Unicode controls for bidi text](https://www.w3.org/International/questions/qa-bidi-unicode-controls) for more information. > **Note:** Avoid using the `placeholder` attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for more information. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed from JavaScript code that directly sets the value of the {{domxref("HTMLInputElement","HTMLInputElement.value")}} property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### size The `size` attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ({{cssxref("font")}} settings in use). This does _not_ set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the [`maxlength`](#maxlength) attribute. ## Using password inputs Password input boxes generally work just like other textual input boxes; the main difference is the obscuring of the content to prevent people near the user from reading the password. ### A simple password input Here we see the most basic password input, with a label established using the {{HTMLElement("label")}} element. ```html <label for="userPassword">Password: </label> <input id="userPassword" type="password" /> ``` {{EmbedLiveSample("A_simple_password_input", 600, 40)}} ### Allowing autocomplete To allow the user's password manager to automatically enter the password, specify the [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) attribute. For passwords, this should typically be one of the following: - `on` - : Allow the browser or a password manager to automatically fill out the password field. This isn't as informative as using either `current-password` or `new-password`. - `off` - : Don't allow the browser or password manager to automatically fill out the password field. Note that some software ignores this value, since it's typically harmful to users' ability to maintain safe password practices. - `current-password` - : Allow the browser or password manager to enter the current password for the site. This provides more information than `on` does, since it lets the browser or password manager automatically enter currently-known password for the site in the field, but not to suggest a new one. - `new-password` - : Allow the browser or password manager to automatically enter a new password for the site; this is used on "change your password" and "new user" forms, on the field asking the user for a new password. The new password may be generated in a variety of ways, depending on the password manager in use. It may fill in a new suggested password, or it might show the user an interface for creating one. ```html <label for="userPassword">Password:</label> <input id="userPassword" type="password" autocomplete="current-password" /> ``` {{EmbedLiveSample("Allowing_autocomplete", 600, 40)}} ### Making the password mandatory To tell the user's browser that the password field must have a valid value before the form can be submitted, specify the Boolean [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute. ```html <label for="userPassword">Password: </label> <input id="userPassword" type="password" required /> <input type="submit" value="Submit" /> ``` {{EmbedLiveSample("Making_the_password_mandatory", 600, 40)}} ### Specifying an input mode If your recommended (or required) password syntax rules would benefit from an alternate text entry interface than the standard keyboard, you can use the [`inputmode`](/en-US/docs/Web/HTML/Element/input#inputmode) attribute to request a specific one. The most obvious use case for this is if the password is required to be numeric (such as a PIN). Mobile devices with virtual keyboards, for example, may opt to switch to a numeric keypad layout instead of a full keyboard, to make entering the password easier. If the PIN is for one-time use, set the [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) attribute to either `off` or `one-time-code` to suggest that it's not saved. ```html <label for="pin">PIN: </label> <input id="pin" type="password" inputmode="numeric" /> ``` {{EmbedLiveSample("Specifying_an_input_mode", 600, 40)}} ### Setting length requirements As usual, you can use the [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) and [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) attributes to establish minimum and maximum acceptable lengths for the password. This example expands on the previous one by specifying that the user's PIN must be at least four and no more than eight digits. The [`size`](/en-US/docs/Web/HTML/Element/input#size) attribute is used to ensure that the password entry control is eight characters wide. ```html <label for="pin">PIN:</label> <input id="pin" type="password" inputmode="numeric" minlength="4" maxlength="8" size="8" /> ``` {{EmbedLiveSample("Setting_length_requirements", 600, 40)}} ### Selecting text As with other textual entry controls, you can use the {{domxref("HTMLInputElement.select", "select()")}} method to select all the text in the password field. #### HTML ```html <label for="userPassword">Password: </label> <input id="userPassword" type="password" size="12" /> <button id="selectAll">Select All</button> ``` #### JavaScript ```js document.getElementById("selectAll").onclick = () => { document.getElementById("userPassword").select(); }; ``` #### Result {{EmbedLiveSample("Selecting_text", 600, 40)}} You can also use {{domxref("HTMLInputElement.selectionStart", "selectionStart")}} and {{domxref("HTMLInputElement.selectionEnd", "selectionEnd")}} to get (or set) what range of characters in the control are currently selected, and {{domxref("HTMLInputElement.selectionDirection", "selectionDirection")}} to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation for an explanation). However, given that the text is obscured, the usefulness of these is somewhat limited. ## Validation If your application has character set restrictions or any other requirement for the actual content of the entered password, you can use the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute to establish a regular expression to be used to automatically ensure that your passwords meet those requirements. In this example, only values consisting of at least four and no more than eight hexadecimal digits are valid. ```html <label for="hexId">Hex ID: </label> <input id="hexId" type="password" pattern="[0-9a-fA-F]{4,8}" title="Enter an ID consisting of 4-8 hexadecimal digits" autocomplete="new-password" /> ``` {{EmbedLiveSample("Validation", 600, 40)}} ## Examples ### Requesting a Social Security number This example only accepts input which matches the format for a [valid United States Social Security Number](https://en.wikipedia.org/wiki/Social_Security_number#Structure). These numbers, used for tax and identification purposes in the US, are in the form "123-45-6789". Assorted rules for what values are permitted in each group exist as well. #### HTML ```html <label for="ssn">SSN:</label> <input type="password" id="ssn" inputmode="numeric" minlength="9" maxlength="12" pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}" required autocomplete="off" /> <br /> <label for="ssn">Value:</label> <span id="current"></span> ``` This uses a [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) which limits the entered value to strings representing legal Social Security numbers. Obviously, this regexp doesn't guarantee a valid SSN (since we don't have access to the Social Security Administration's database), but it does ensure the number could be one; it generally avoids values that cannot be valid. In addition, it allows the three groups of digits to be separated by a space, a dash ("-"), or nothing. The [`inputmode`](/en-US/docs/Web/HTML/Element/input#inputmode) is set to `numeric` to encourage devices with virtual keyboards to switch to a numeric keypad layout for easier entry. The [`minlength`](/en-US/docs/Web/HTML/Element/input#minlength) and [`maxlength`](/en-US/docs/Web/HTML/Element/input#maxlength) attributes are set to 9 and 12, respectively, to require that the value be at least nine and no more than 12 characters (the former without separating characters between the groups of digits and the latter with them). The [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute is used to indicate that this control must have a value. Finally, [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) is set to `off` to avoid password managers and session restore features trying to set its value, since this isn't a password at all. #### JavaScript This is just some simple code to display the entered SSN onscreen so you can see it. Obviously this defeats the purpose of a password field, but it's helpful for experimenting with the `pattern`. ```js const ssn = document.getElementById("ssn"); const current = document.getElementById("current"); ssn.oninput = (event) => { current.textContent = ssn.value; }; ``` #### Result {{EmbedLiveSample("Requesting_a_Social_Security_number", 600, 60)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing a password, or empty </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported Common Attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#inputmode"><code>inputmode</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#maxlength"><code>maxlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#minlength"><code>minlength</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#pattern"><code>pattern</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#placeholder"><code>placeholder</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#required"><code>required</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#size"><code>size</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>selectionStart</code>, <code>selectionEnd</code>, <code>selectionDirection</code>, and <code>value</code> </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.setRangeText", "setRangeText()")}}, and {{domxref("HTMLInputElement.setSelectionRange", "setSelectionRange()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/reset/index.md
--- title: <input type="reset"> slug: Web/HTML/Element/input/reset page-type: html-element browser-compat: html.elements.input.type_reset --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`reset`** are rendered as buttons, with a default {{domxref("Element/click_event", "click")}} event handler that resets all inputs in the form to their initial values. {{EmbedInteractiveExample("pages/tabbed/input-reset.html", "tabbed-standard")}} > **Note:** You should usually avoid including reset buttons in your forms. They're rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the [submit button](/en-US/docs/Web/HTML/Element/input/submit)). ## Value An `<input type="reset">` element's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string that is used as the button's label providing the button with an {{glossary("accessible description")}}. Buttons such as `reset` don't have a value otherwise. ### Setting the value attribute ```html <input type="reset" value="Reset the form" /> ``` {{EmbedLiveSample("Setting_the_value_attribute", 650, 30)}} ### Omitting the value attribute If you don't specify a `value`, you get a button with the default label (typically "Reset," but this will vary depending on the {{Glossary("user agent")}}): ```html <input type="reset" /> ``` {{EmbedLiveSample("Omitting_the_value_attribute", 650, 30)}} ## Using reset buttons `<input type="reset">` buttons are used to reset forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use [`<input type="button">`](/en-US/docs/Web/HTML/Element/input/button), or better still, a {{htmlelement("button")}} element. ### A simple reset button We'll begin by creating a simple reset button: ```html <form> <div> <label for="example">Type in some sample text</label> <input id="example" type="text" /> </div> <div> <input type="reset" value="Reset the form" /> </div> </form> ``` This renders like so: {{EmbedLiveSample("A_simple_reset_button", 650, 100)}} Try entering some text into the text field, and then pressing the reset button. ### Adding a reset keyboard shortcut To add a keyboard shortcut to a reset button — just as you would with any {{HTMLElement("input")}} for which it makes sense — you use the [`accesskey`](/en-US/docs/Web/HTML/Global_attributes#accesskey) global attribute. In this example, <kbd>r</kbd> is specified as the access key (you'll need to press <kbd>r</kbd> plus the particular modifier keys for your browser/OS combination; see [`accesskey`](/en-US/docs/Web/HTML/Global_attributes#accesskey) for a useful list of those). ```html <form> <div> <label for="example">Type in some sample text</label> <input id="example" type="text" /> </div> <div> <input type="reset" value="Reset the form" accesskey="r" /> </div> </form> ``` {{EmbedLiveSample("Adding_a_reset_keyboard_shortcut", 650, 100)}} The problem with the above example is that there's no way for the user to know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute) can also help, although it's not a complete solution for accessibility purposes. ### Disabling and enabling a reset button To disable a reset button, specify the [`disabled`](/en-US/docs/Web/HTML/Element/input#disabled) attribute on it, like so: ```html <input type="reset" value="Disabled" disabled /> ``` You can enable and disable buttons at run time by setting `disabled` to `true` or `false`; in JavaScript this looks like `btn.disabled = true` or `btn.disabled = false`. > **Note:** See the [`<input type="button">`](/en-US/docs/Web/HTML/Element/input/button#disabling_and_enabling_a_button) page for more ideas about enabling and disabling buttons. ## Validation Buttons don't participate in constraint validation; they have no real value to be constrained. ## Examples We've included simple examples above. There isn't really anything more to say about reset buttons. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>A string used as the button's label</td> </tr> <tr> <td><strong>Events</strong></td> <td>{{domxref("Element/click_event", "click")}}</td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#type"><code>type</code></a> and <a href="/en-US/docs/Web/HTML/Element/input#value"><code>value</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td>None</td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role"><code>button</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it. - [Forms and buttons](/en-US/docs/Learn/Forms/Basic_native_form_controls#actual_buttons) - [HTML forms](/en-US/docs/Learn/Forms) - The {{HTMLElement("button")}} element - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/date/index.md
--- title: <input type="date"> slug: Web/HTML/Element/input/date page-type: html-element browser-compat: html.elements.input.type_date --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of **`type="date"`** create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface. The resulting value includes the year, month, and day, but _not_ the time. The {{HTMLElement("input/time", "time")}} and {{HTMLElement("input/datetime-local", "datetime-local")}} input types support time and date+time input. {{EmbedInteractiveExample("pages/tabbed/input-date.html", "tabbed-shorter")}} The input UI generally varies from browser to browser; see [Browser compatibility](#browser_compatibility) for further details. In unsupported browsers, the control degrades gracefully to [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text). ## Value A string representing the date entered in the input. The date is formatted according to [Date strings format](/en-US/docs/Web/HTML/Date_and_time_formats#date_strings). You can set a default value for the input with a date inside the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute, like so: ```html <input type="date" value="2017-06-01" /> ``` {{EmbedLiveSample('Value', 600, 40)}} > **Note:** The displayed date format will differ from the actual `value` — the displayed date is formatted _based on the locale of the user's browser_, but the parsed `value` is always formatted `yyyy-mm-dd`. You can get and set the date value in JavaScript with the {{domxref("HTMLInputElement")}} `value` and `valueAsNumber` properties. For example: ```js const dateControl = document.querySelector('input[type="date"]'); dateControl.value = "2017-06-01"; console.log(dateControl.value); // prints "2017-06-01" console.log(dateControl.valueAsNumber); // prints 1496275200000, a JavaScript timestamp (ms) ``` This code finds the first {{HTMLElement("input")}} element whose `type` is `date`, and sets its value to `2017-06-01` (June 1st, 2017). It then reads that value back in string and number formats. ## Additional attributes The attributes common to all {{HTMLElement("input")}} elements apply to the `date` inputs as well, but might not influence its presentation. For example `size` and `placeholder` might not work. `date` inputs have the following additional attributes. ### max The latest date to accept. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element occurs afterward, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `max` attribute isn't a possible date string in the format `yyyy-mm-dd`, then the element has no maximum date value. If both the `max` and `min` attributes are set, this value must be a date string **later than or equal to** the one in the `min` attribute. ### min The earliest date to accept. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element occurs beforehand, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `min` attribute isn't a possible date string in the format `yyyy-mm-dd`, then the element has no minimum date value. If both the `max` and `min` attributes are set, this value must be a date string **earlier than or equal to** the one in the `max` attribute. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `date` inputs, the value of `step` is given in days; and is treated as a number of milliseconds equal to 86,400,000 times the `step` value (the underlying numeric value is in milliseconds). The default value of `step` is 1, indicating 1 day. > **Note:** Specifying `any` as the value for `step` has the same effect as `1` for `date` inputs. ## Using date inputs Date inputs provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user's locale. In this section, we'll look at basic and then more complex uses of `<input type="date">`. ### Basic uses of date The simplest use of `<input type="date">` involves one `<input>` combined with its {{htmlelement("label")}}, as seen below: ```html <form action="https://example.com"> <label> Enter your birthday: <input type="date" name="bday" /> </label> <p><button>Submit</button></p> </form> ``` {{EmbedLiveSample('Basic_uses_of_date', 600, 40)}} This HTML submits the entered date under the key `bday` to `https://example.com` — resulting in a URL like `https://example.com/?bday=1955-06-08`. ### Setting maximum and minimum dates You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to restrict the dates that can be chosen by the user. In the following example, we set a minimum date of `2017-04-01` and a maximum date of `2017-04-30`: ```html <form> <label> Choose your preferred party date: <input type="date" name="party" min="2017-04-01" max="2017-04-30" /> </label> </form> ``` {{EmbedLiveSample('Setting_maximum_and_minimum_dates', 600, 40)}} The result is that only days in April 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside April 2017 can't be selected in the picker widget. > **Note:** You _should_ be able to use the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute to vary the number of days jumped each time the date is incremented (e.g. to only make Saturdays selectable). However, this does not seem to be in any implementation at the time of writing. ### Controlling input size `<input type="date">` doesn't support form sizing attributes such as [`size`](/en-US/docs/Web/HTML/Element/input#size). Prefer [CSS](/en-US/docs/Web/CSS) for sizing it. ## Validation By default, `<input type="date">` doesn't validate the entered value beyond its format. The interfaces generally don't let you enter anything that isn't a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type `text` (like the 32nd of April). If you use [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) to restrict the available dates (see [Setting maximum and minimum dates](#setting_maximum_and_minimum_dates)), supporting browsers will display an error if you try to submit a date that is out of bounds. However, you'll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn't fully supported on the user's device. You can also use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute to make filling in the date mandatory — an error will be displayed if you try to submit an empty date field. This should work in most browsers, even if they fall back to a text input. Let's look at an example of minimum and maximum dates, and also made a field required: ```html <form> <label> Choose your preferred party date (required, April 1st to 20th): <input type="date" name="party" min="2017-04-01" max="2017-04-20" required /> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form> ``` If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: {{EmbedLiveSample('Validation', 600, 100)}} Here's the CSS used in the above example. We make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} [pseudo-elements](/en-US/docs/Web/CSS/Pseudo-elements) to add an icon next to the input, based on whether the current value is valid. We had to put the icon on a {{htmlelement("span")}} next to the input, not on the input itself, because in Chrome at least the input's generated content is placed inside the form control, and can't be styled or shown effectively. ```css label { display: flex; align-items: center; } span::after { padding-left: 5px; } input:invalid + span::after { content: "✖"; } input:valid + span::after { content: "✓"; } ``` > **Warning:** Client-side form validation _is no substitute_ for validating on the server. It's easy for someone to modify the HTML, or bypass your HTML entirely and submit the data directly to your server. If your server fails to validate the received data, disaster could strike with data that is badly-formatted, too large, of the wrong type, etc. ## Handling browser support Browsers that don't support this input type gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling. The second problem is the more serious one; with date input supported, the value is normalized to the format `yyyy-mm-dd`. But with a text input, the browser has no recognition of what format the date should be in, and there are many formats in which people write dates. For example: - `ddmmyyyy` - `dd/mm/yyyy` - `mm/dd/yyyy` - `dd-mm-yyyy` - `mm-dd-yyyy` - `Month dd, yyyy` One way around this is the [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute on your date input. Even though the date picker doesn't use it, the text input fallback will. For example, try viewing the following in an unsupporting browser: ```html <form> <label> Enter your birthday: <input type="date" name="bday" required pattern="\d{4}-\d{2}-\d{2}" /> <span class="validity"></span> </label> <p> <button>Submit</button> </p> </form> ``` {{EmbedLiveSample('Handling_browser_support', 600, 100)}} If you submit it, you'll see that the browser displays an error and highlights the input as invalid if your entry doesn't match the pattern `####-##-##` (where `#` is a digit from 0 to 9). Of course, this doesn't stop people from entering invalid dates, or incorrect formats. So we still have a problem. ```css hidden span { position: relative; } span::after { right: -18px; position: absolute; } input:invalid + span::after { content: "✖"; } input:valid + span::after { content: "✓"; } ``` At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a JavaScript library such as [jQuery date picker](https://jqueryui.com/datepicker/). ## Examples In this example, we create 2 sets of UI elements for choosing dates: a native `<input type="date">` picker and a set of 3 {{htmlelement("select")}} elements for older browsers that don't support the native date input. {{EmbedLiveSample('Examples', 600, 100)}} ### HTML The HTML looks like so: ```html <form> <div class="nativeDatePicker"> <label for="bday">Enter your birthday:</label> <input type="date" id="bday" name="bday" /> <span class="validity"></span> </div> <p class="fallbackLabel">Enter your birthday:</p> <div class="fallbackDatePicker"> <span> <label for="day">Day:</label> <select id="day" name="day"></select> </span> <span> <label for="month">Month:</label> <select id="month" name="month"> <option selected>January</option> <option>February</option> <option>March</option> <option>April</option> <option>May</option> <option>June</option> <option>July</option> <option>August</option> <option>September</option> <option>October</option> <option>November</option> <option>December</option> </select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"></select> </span> </div> </form> ``` The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.) ```css hidden span { padding-left: 5px; } input:invalid + span::after { content: "✖"; } input:valid + span::after { content: "✓"; } ``` ### JavaScript The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports `<input type="date">`. We create a new {{htmlelement("input")}} element, try setting its `type` to `date`, then immediately check what its type is — unsupporting browsers will return `text`, because the `date` type falls back to type `text`. If `<input type="date">` isn't supported, we hide the native picker and show the fallback ({{htmlelement("select")}}) instead. ```js // Obtain UI widgets const nativePicker = document.querySelector(".nativeDatePicker"); const fallbackPicker = document.querySelector(".fallbackDatePicker"); const fallbackLabel = document.querySelector(".fallbackLabel"); const yearSelect = document.querySelector("#year"); const monthSelect = document.querySelector("#month"); const daySelect = document.querySelector("#day"); // hide fallback initially fallbackPicker.style.display = "none"; fallbackLabel.style.display = "none"; // test whether a new date input falls back to a text input or not const test = document.createElement("input"); try { test.type = "date"; } catch (e) { console.log(e.message); } // if it does, run the code inside the if () {} block if (test.type === "text") { // hide the native picker and show the fallback nativePicker.style.display = "none"; fallbackPicker.style.display = "block"; fallbackLabel.style.display = "block"; // populate the days and years dynamically // (the months are always the same, therefore hardcoded) populateDays(monthSelect.value); populateYears(); } function populateDays(month) { // delete the current set of <option> elements out of the // day <select>, ready for the next set to be injected while (daySelect.firstChild) { daySelect.removeChild(daySelect.firstChild); } // Create variable to hold new number of days to inject let dayNum; // 31 or 30 days? if ( [ "January", "March", "May", "July", "August", "October", "December", ].includes(month) ) { dayNum = 31; } else if (["April", "June", "September", "November"].includes(month)) { dayNum = 30; } else { // If month is February, calculate whether it is a leap year or not const year = yearSelect.value; const isLeap = new Date(year, 1, 29).getMonth() === 1; dayNum = isLeap ? 29 : 28; } // inject the right number of new <option> elements into the day <select> for (let i = 1; i <= dayNum; i++) { const option = document.createElement("option"); option.textContent = i; daySelect.appendChild(option); } // if previous day has already been set, set daySelect's value // to that day, to avoid the day jumping back to 1 when you // change the year if (previousDay) { daySelect.value = previousDay; // If the previous day was set to a high number, say 31, and then // you chose a month with less total days in it (e.g. February), // this part of the code ensures that the highest day available // is selected, rather than showing a blank daySelect if (daySelect.value === "") { daySelect.value = previousDay - 1; } if (daySelect.value === "") { daySelect.value = previousDay - 2; } if (daySelect.value === "") { daySelect.value = previousDay - 3; } } } function populateYears() { // get this year as a number const date = new Date(); const year = date.getFullYear(); // Make this year, and the 100 years before it available in the year <select> for (let i = 0; i <= 100; i++) { const option = document.createElement("option"); option.textContent = year - i; yearSelect.appendChild(option); } } // when the month or year <select> values are changed, rerun populateDays() // in case the change affected the number of available days yearSelect.onchange = () => { populateDays(monthSelect.value); }; monthSelect.onchange = () => { populateDays(monthSelect.value); }; //preserve day selection let previousDay; // update what day has been set to previously // see end of populateDays() for usage daySelect.onchange = () => { previousDay = daySelect.value; }; ``` > **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! You'll need to take this into consideration when developing production apps. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing a date in YYYY-MM-DD format, or empty </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#step"><code>step</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>list</code>, <code>value</code>, <code>valueAsDate</code>, <code>valueAsNumber</code>. </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}} - [Date and Time picker tutorial](/en-US/docs/Learn/Forms/HTML5_input_types#date_and_time_pickers) - [Date and time formats used in HTML](/en-US/docs/Web/HTML/Date_and_time_formats) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/datetime-local/index.md
--- title: <input type="datetime-local"> slug: Web/HTML/Element/input/datetime-local page-type: html-element browser-compat: html.elements.input.type_datetime-local --- {{HTMLSidebar}} {{htmlelement("input")}} elements of type **`datetime-local`** create input controls that let the user easily enter both a date and a time, including the year, month, and day as well as the time in hours and minutes. {{EmbedInteractiveExample("pages/tabbed/input-datetime-local.html", "tabbed-shorter")}} The control's UI varies in general from browser to browser. In browsers with no support, these degrade gracefully to simple [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text) controls. The control is intended to represent _a local date and time_, not necessarily _the user's local date and time_. In other words, the input allows any valid combination of year, month, day, hour, and minute—even if such a combination is invalid in the user's local time zone (such as the one hour within a daylight saving time spring-forward transition gap). ## Value A string representing the value of the date entered into the input. The format of the date and time value used by this input type is described in [Local date and time strings](/en-US/docs/Web/HTML/Date_and_time_formats#local_date_and_time_strings). You can set a default value for the input by including a date and time inside the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute, like so: ```html <label for="party">Enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30" /> ``` {{ EmbedLiveSample('Value', 600, 60) }} One thing to note is that the displayed date and time formats differ from the actual `value`; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time `value` is always formatted `YYYY-MM-DDThh:mm`. When the above value is submitted to the server, for example, it will look like `partydate=2024-06-01T08:30`. > **Note:** Also bear in mind that if such data is submitted via HTTP [`GET`](/en-US/docs/Web/HTTP/Methods/GET), the colon character will need to be escaped for inclusion in the URL parameters, e.g. `partydate=2024-06-01T08%3A30`. See {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} for one way to do this. You can also get and set the date value in JavaScript using the {{domxref("HTMLInputElement")}} `value` property, for example: ```js const dateControl = document.querySelector('input[type="datetime-local"]'); dateControl.value = "2017-06-01T08:30"; ``` ## Additional attributes In addition to the attributes common to all {{HTMLElement("input")}} elements, `datetime-local` inputs offer the following attributes. ### max The latest date and time to accept. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element is later than this timestamp, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `max` attribute isn't a valid string that follows the format `YYYY-MM-DDThh:mm`, then the element has no maximum value. This value must specify a date string later than or equal to the one specified by the `min` attribute. ### min The earliest date and time to accept; timestamps earlier than this will cause the element to fail [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `min` attribute isn't a valid string that follows the format `YYYY-MM-DDThh:mm`, then the element has no minimum value. This value must specify a date string earlier than or equal to the one specified by the `max` attribute. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `datetime-local` inputs, the value of `step` is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of `step` is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds). _At this time, it's unclear what a value of `any` means for `step` when used with `datetime-local` inputs. This will be updated as soon as that information is determined._ ## Using datetime-local inputs Date/time inputs are convenient for the developer; they provide an easy UI for choosing dates and times, and they normalize the data format sent to the server, regardless of the user's locale. However, it is important to consider your users. Don't require your users to enter data that is not needed for your app to function. ### Controlling input size `<input type="datetime-local">` doesn't support form control sizing attributes such as [`size`](/en-US/docs/Web/HTML/Element/input#size). You'll have to resort to [CSS](/en-US/docs/Web/CSS) for customizing the sizes of these elements. ### Setting timezones One thing the `datetime-local` input type doesn't provide is a way to set the time zone and/or locale of the date/time control. This was available in the `datetime` input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control. For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a [`hidden`](/en-US/docs/Web/HTML/Element/input/hidden) input type. For example: ```html <input type="hidden" id="timezone" name="timezone" value="-08:00" /> ``` On the other hand, if you were required to allow the user to enter a time zone along with a date/time input, you could have a {{htmlelement("select")}} element to enable the user to set the right time zone by choosing a particular location from among a set of locations: ```html <select name="timezone" id="timezone"> <option value="Pacific/Kwajalein">Eniwetok, Kwajalein</option> <option value="Pacific/Midway">Midway Island, Samoa</option> <option value="Pacific/Honolulu">Hawaii</option> <option value="Pacific/Marquesas">Taiohae</option> <!-- and so on --> </select> ``` In either case, the date/time and time zone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side. ## Validation By default, `<input type="datetime-local">` does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of April). You can use [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) to restrict the available dates (see [Setting maximum and minimum dates](#setting_maximum_and_minimum_dates_and_times)), and you can use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute to make filling in the date/time mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds or an empty date field. Let's look at an example; here we've set minimum and maximum date/time values, and also made the field required: ```html <form> <div> <label for="party"> Choose your preferred party date and time (required, June 1st 8.30am to June 30th 4.30pm): </label> <input id="party" type="datetime-local" name="partydate" min="2017-06-01T08:30" max="2017-06-30T16:30" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Book party!" /> </div> </form> ``` If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now: {{ EmbedLiveSample('Validation', 600, 120) }} Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether the current value is valid. We put the icons on a {{htmlelement("span")}} next to the input. ```css div { margin-bottom: 10px; display: flex; align-items: center; } label { display: inline-block; width: 300px; } input:invalid + span::after { content: "✖"; padding-left: 5px; } input:valid + span::after { content: "✓"; padding-left: 5px; } ``` > **Warning:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, problems can arise when improperly-formatted data is submitted (or data that is too large, is of the wrong type, and so forth). > **Note:** With a `datetime-local` input, the date value is always normalized to the format `YYYY-MM-DDThh:mm`. ## Examples ### Basic uses of datetime-local The simplest use of `<input type="datetime-local">` involves a basic `<input>` and {{htmlelement("label")}} element combination, as seen below: ```html <form> <label for="party">Enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" /> </form> ``` {{ EmbedLiveSample('Basic_uses_of_datetime-local', 600, 40) }} ### Setting maximum and minimum dates and times You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to restrict the dates/times that can be chosen by the user. In the following example, we are setting a minimum datetime of `2024-06-01T08:30` and a maximum datetime of `2024-06-30T16:30`: ```html <form> <label for="party">Enter a date and time for your party booking:</label> <input id="party" type="datetime-local" name="partydate" min="2024-06-01T08:30" max="2024-06-30T16:30" /> </form> ``` {{ EmbedLiveSample('Setting_maximum_and_minimum_dates_and_times', 600, 40) }} Only days in June 2024 can be selected. Depending on what browser you are using, times outside the specified values might not be selectable. In other browsers, invalid dates and times are selectable but will match {{CSSXref(":invalid")}} and {{CSSXref(":out-of-range")}} and will fail [validation](#validation). In some browsers (Chrome and Edge), only the "days" part of the date value will be editable, and dates outside June can't be scrolled. In others (Safari), the date picker will appear to allow any date, but the value will be clamped to the valid range when a date is selected. The valid range included all times between the `min` and `max` values; the time of day is only constrained on the first and last dates in the range. > **Note:** You should be able to use the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing a date and time (in the local time zone), or empty. </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#step"><code>step</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>list</code>, <code>value</code>, <code>valueAsNumber</code>. </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}} - [`<input type="date">`](/en-US/docs/Web/HTML/Element/input/date) and [`<input type="time">`](/en-US/docs/Web/HTML/Element/input/time) - [Date and time formats used in HTML](/en-US/docs/Web/HTML/Date_and_time_formats) - [Date and Time picker tutorial](/en-US/docs/Learn/Forms/Basic_native_form_controls#date_and_time_picker) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/range/index.md
--- title: <input type="range"> slug: Web/HTML/Element/input/range page-type: html-element browser-compat: html.elements.input.type_range --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`range`** let the user specify a numeric value which must be no less than a given value, and no more than another given value. The precise value, however, is not considered important. This is typically represented using a slider or dial control rather than a text entry box like the {{HTMLElement('input/number', 'number')}} input type. Because this kind of widget is imprecise, it should only be used if the control's exact value isn't important. {{EmbedInteractiveExample("pages/tabbed/input-range.html", "tabbed-standard")}} If the user's browser doesn't support type `range`, it will fall back and treat it as a `{{HTMLElement('input/text', 'text')}}` input. ### Validation There is no pattern validation available; however, the following forms of automatic validation are performed: - If the [`value`](/en-US/docs/Web/HTML/Element/input#value) is set to something which can't be converted into a valid floating-point number, validation fails because the input is suffering from a bad input. - The value won't be less than [`min`](/en-US/docs/Web/HTML/Element/input#min). The default is 0. - The value won't be greater than [`max`](/en-US/docs/Web/HTML/Element/input#max). The default is 100. - The value will be a multiple of [`step`](/en-US/docs/Web/HTML/Element/input#step). The default is 1. ### Value The [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string which contains a string representation of the selected number. The value is never an empty string (`""`). The default value is halfway between the specified minimum and maximum—unless the maximum is actually less than the minimum, in which case the default is set to the value of the `min` attribute. The algorithm for determining the default value is: ```js defaultValue = rangeElem.max < rangeElem.min ? rangeElem.min : rangeElem.min + (rangeElem.max - rangeElem.min) / 2; ``` If an attempt is made to set the value lower than the minimum, it is set to the minimum. Similarly, an attempt to set the value higher than the maximum results in it being set to the maximum. ## Additional attributes In addition to the attributes shared by all {{HTMLElement("input")}} elements, range inputs offer the following attributes. ### list The value of the `list` attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. See the [adding tick marks](#adding_tick_marks) below for an example of how the options on a range are denoted in supported browsers. ### max The greatest value in the range of permitted values. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element exceeds this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the [`max`](/en-US/docs/Web/HTML/Attributes/max) attribute isn't a number, then the element has no maximum value. This value must be greater than or equal to the value of the [`min`](/en-US/docs/Web/HTML/Attributes/min) attribute. See the HTML [`max`](/en-US/docs/Web/HTML/Attributes/max) attribute. ### min The lowest value in the range of permitted values. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) of the element is less than this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If a value is specified for `min` that isn't a valid number, the input has no minimum value. This value must be less than or equal to the value of the [`max`](/en-US/docs/Web/HTML/Attributes/max) attribute. See the HTML [`min`](/en-US/docs/Web/HTML/Attributes/min) attribute. > **Note:** If the `min` and `max` values are equal or the `max` value is lower than the `min` value the user will not be able to interact with the range. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to. Only values that match the specified stepping interval ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, or an appropriate default value if neither of those is provided) are valid. The `step` attribute can also be set to the `any` string value. This `step` value means that no stepping interval is implied and any value is allowed in the specified range (barring other constraints, such as [`min`](#min) and [`max`](#max)). See the [Setting step to the `any` value](#setting_step_to_any) example for how this works in supported browsers. > **Note:** When the value entered by a user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round off the value to the nearest valid value, preferring to round numbers up when there are two equally close options. The default stepping value for `range` inputs is 1, allowing only integers to be entered, _unless_ the stepping base is not an integer; for example, if you set `min` to -10 and `value` to 1.5, then a `step` of 1 will allow only values such as 1.5, 2.5, 3.5,… in the positive direction and -0.5, -1.5, -2.5,… in the negative direction. See the [HTML `step` attribute](/en-US/docs/Web/HTML/Attributes/step). ## Non-standard Attributes ### orient Similar to the -moz-orient non-standard CSS property impacting the {{htmlelement('progress')}} and {{htmlelement('meter')}} elements, the `orient` attribute defines the orientation of the range slider. Values include `horizontal`, meaning the range is rendered horizontally, and `vertical`, where the range is rendered vertically. > **Note:** The following input attributes do not apply to the input range: `accept`, `alt`, `checked`, `dirname`, `formaction`, `formenctype`, `formmethod`, `formnovalidate`, `formtarget`, `height`, `maxlength`, `minlength`, `multiple`, `pattern`, `placeholder`, `readonly`, `required`, `size`, and `src`. Any of these attributes, if included, will be ignored. ## Examples While the `number` type lets users enter a number with optional constraints forcing their value to be between a minimum and a maximum value, it does require that they enter a specific value. The `range` input type lets you ask the user for a value in cases where the user may not even care—or know—what the specific numeric value selected is. A few examples of situations in which range inputs are commonly used: - Audio controls such as volume and balance, or filter controls. - Color configuration controls such as color channels, transparency, brightness, etc. - Game configuration controls such as difficulty, visibility distance, world size, and so forth. - Password length for a password manager's generated passwords. As a rule, if the user is more likely to be interested in the percentage of the distance between minimum and maximum values than the actual number itself, a range input is a great candidate. For example, in the case of a home stereo volume control, users typically think "set volume at halfway to maximum" instead of "set volume to 0.5". ### Specifying the minimum and maximum By default, the minimum is 0 and the maximum is 100. If that's not what you want, you can easily specify different bounds by changing the values of the [`min`](/en-US/docs/Web/HTML/Element/input#min) and/or [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes. These can be any floating-point value. For example, to ask the user for a value between -10 and 10, you can use: ```html <input type="range" min="-10" max="10" /> ``` {{EmbedLiveSample("Specifying_the_minimum_and_maximum", 600, 40)}} ### Setting the value's granularity By default, the granularity is 1, meaning the value is always an integer. To control the granularity, you can change the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute. For example, If you need a value to be halfway between 5 and 10, you should set the value of `step` to 0.5: #### Setting the step attribute ```html <input type="range" min="5" max="10" step="0.5" /> ``` {{EmbedLiveSample("Setting_the_step_attribute", 600, 40)}} #### Setting step to `any` If you want to accept any value regardless of how many decimal places it extends to, you can specify a value of `any` for the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute: ##### HTML ```html <input id="pi_input" type="range" min="0" max="3.14" step="any" /> <p>Value: <output id="value"></output></p> ``` ##### JavaScript ```js const value = document.querySelector("#value"); const input = document.querySelector("#pi_input"); value.textContent = input.value; input.addEventListener("input", (event) => { value.textContent = event.target.value; }); ``` {{EmbedLiveSample("Setting_step_to_any", 600, 75)}} This example lets the user select any value between 0 and π without any restriction on the fractional part of the value selected. JavaScript is used to show how the value changes as the user interacts with the range. ### Adding tick marks To add tick marks to a range control, include the `list` attribute, giving it the `id` of a {{HTMLElement("datalist")}} element which defines a series of tick marks on the control. Each point is represented using an {{HTMLElement("option")}} element with its [`value`](/en-US/docs/Web/HTML/Element/option#value) set to the range's value at which a mark should be drawn. #### HTML ```html <label for="temp">Choose a comfortable temperature:</label><br /> <input type="range" id="temp" name="temp" list="markers" /> <datalist id="markers"> <option value="0"></option> <option value="25"></option> <option value="50"></option> <option value="75"></option> <option value="100"></option> </datalist> ``` #### Result {{EmbedLiveSample("Adding tick marks", 600, 50)}} ### Using the same datalist for multiple range controls To help you from repeating code you can reuse that same {{HTMLElement("datalist")}} for multiple `<input type="range">` elements, and other {{HTMLElement("input")}} types. > **Note:** If you also want to [show the labels](#adding_labels) as in the example below then you would need a `datalist` for each range input. #### HTML ```html <p> <label for="temp1">Temperature for room 1:</label> <input type="range" id="temp1" name="temp1" list="values" /> </p> <p> <label for="temp2">Temperature for room 2:</label> <input type="range" id="temp2" name="temp2" list="values" /> </p> <p> <label for="temp3">Temperature for room 3:</label> <input type="range" id="temp3" name="temp3" list="values" /> </p> <datalist id="values"> <option value="0" label="0"></option> <option value="25" label="25"></option> <option value="50" label="50"></option> <option value="75" label="75"></option> <option value="100" label="100"></option> </datalist> ``` #### Result {{EmbedLiveSample("Using the same datalist for multiple range controls")}} ### Adding labels You can label tick marks by giving the `<option>` elements `label` attributes. However, the label content will not be displayed by default. You can use CSS to show the labels and to position them correctly. Here's one way you could do this. #### HTML ```html <label for="tempB">Choose a comfortable temperature:</label><br /> <input type="range" id="tempB" name="temp" list="values" /> <datalist id="values"> <option value="0" label="very cold!"></option> <option value="25" label="cool"></option> <option value="50" label="medium"></option> <option value="75" label="getting warm!"></option> <option value="100" label="hot!"></option> </datalist> ``` #### CSS ```css datalist { display: flex; flex-direction: column; justify-content: space-between; writing-mode: vertical-lr; width: 200px; } option { padding: 0; } input[type="range"] { width: 200px; margin: 0; } ``` #### Result {{EmbedLiveSample("Adding labels")}} ### Creating vertical range controls By default, browsers render range inputs as sliders with the knob sliding left and right. To create a vertical range, wherein the knob slides up and down, set the CSS {{cssxref('appearance')}} property to `slider-vertical` and include the non-standard `orient` attribute for Firefox. #### Horizontal range control Consider this range control: ```html <input type="range" id="volume" min="0" max="11" value="7" step="1" /> ``` {{EmbedLiveSample("Horizontal_range_control", 200, 40)}} This control is horizontal (at least on most if not all major browsers; others might vary). #### Using the appearance property The {{cssxref('appearance')}} property has a non-standard value of `slider-vertical` that, well, makes sliders vertical. We use the same HTML as in the previous examples: ```html <input type="range" min="0" max="11" value="7" step="1" /> ``` We target just the inputs with a type of range: ```css input[type="range"] { appearance: slider-vertical; } ``` {{EmbedLiveSample("Using_the_appearance_property", 200, 200)}} #### Using the orient attribute In Firefox only, there is a non-standard `orient` property. Use similar HTML as in the previous examples, we add the attribute with a value of `vertical`: ```html <input type="range" min="0" max="11" value="7" step="1" orient="vertical" /> ``` {{EmbedLiveSample("Using_the_orient_attribute", 200, 200)}} #### writing-mode: bt-lr The {{cssxref('writing-mode')}} property should generally not be used to alter text direction for internationalization or localization purposes, but can be used for special effects. We use the same HTML as in the previous examples: ```html <input type="range" min="0" max="11" value="7" step="1" /> ``` We target just the inputs with a type of range, changing the writing mode from the default to `bt-lr`, or bottom-to-top and left-to-right: ```css input[type="range"] { writing-mode: bt-lr; } ``` {{EmbedLiveSample("writing-mode_bt-lr", 200, 40)}} #### Putting it all together As each of the above examples works in different browsers, you can put all of them in a single example to make it work cross browser: We keep the `orient` attribute with a value of `vertical` for Firefox: ```html <input type="range" min="0" max="11" value="7" step="1" orient="vertical" /> ``` We target just the `input`s with a `type` of `range` and `orient` set to `vertical`, changing the `writing-mode` from the default to `bt-lr`, or bottom-to-top and left-to-right, for pre-Blink versions of Edge, and add `appearance: slider-vertical` which is supported in Blink and Webkit browsers: ```css input[type="range"][orient="vertical"] { writing-mode: bt-lr; appearance: slider-vertical; } ``` {{EmbedLiveSample("Putting_it_all_together", 200, 200)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string containing the string representation of the selected numeric value; use {{domxref("HTMLInputElement.valueAsNumber", "valueAsNumber")}} to get the value as a number. </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#max"><code>max</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#min"><code>min</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#step"><code>step</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>list</code>, <code>value</code>, and <code>valueAsNumber</code> </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.stepDown", "stepDown()")}} and {{domxref("HTMLInputElement.stepUp", "stepUp()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td> <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/slider_role">slider</a></code> </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML Forms](/en-US/docs/Learn/Forms) - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface it's based upon - [`<input type="number">`](/en-US/docs/Web/HTML/Element/input/number) - {{domxref('validityState.rangeOverflow')}} and {{domxref('validityState.rangeUnderflow')}} - [Controlling multiple parameters with ConstantSourceNode](/en-US/docs/Web/API/Web_Audio_API/Controlling_multiple_parameters_with_ConstantSourceNode) - [Styling the range element](https://css-tricks.com/sliding-nightmare-understanding-range-input/) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/file/index.md
--- title: <input type="file"> slug: Web/HTML/Element/input/file page-type: html-element browser-compat: html.elements.input.type_file --- {{HTMLSidebar}} {{HTMLElement("input")}} elements with **`type="file"`** let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using [form submission](/en-US/docs/Learn/Forms), or manipulated using JavaScript code and [the File API](/en-US/docs/Web/API/File_API/Using_files_from_web_applications). {{EmbedInteractiveExample("pages/tabbed/input-file.html", "tabbed-shorter")}} ## Value A file input's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the value is an empty string (`""`). When the user selected multiple files, the `value` represents the first file in the list of files they selected. The other files can be identified using the [input's `HTMLInputElement.files` property](/en-US/docs/Web/API/File_API/Using_files_from_web_applications#getting_information_about_selected_files). > **Note:** The value is [always the file's name prefixed with `C:\fakepath\`](https://html.spec.whatwg.org/multipage/input.html#fakepath-srsly), which isn't the real path of the file. This is to prevent malicious software from guessing the user's file structure. ## Additional attributes In addition to the common attributes shared by all {{HTMLElement("input")}} elements, inputs of type `file` also support the following attributes. ### accept The [`accept`](/en-US/docs/Web/HTML/Attributes/accept) attribute value is a string that defines the file types the file input should accept. This string is a comma-separated list of **[unique file type specifiers](#unique_file_type_specifiers)**. 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 a given format. 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,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" /> ``` ### capture The [`capture`](/en-US/docs/Web/HTML/Attributes/capture) attribute value is a string that specifies which camera to use for capture of image or video data, if the [`accept`](/en-US/docs/Web/HTML/Attributes/accept) attribute indicates that the input should be of one of those types. A value of `user` indicates that the user-facing camera and/or microphone should be used. A value of `environment` specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing, the {{Glossary("user agent")}} is free to decide on its own what to do. If the requested facing mode isn't available, the user agent may fall back to its preferred default mode. > **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. ### multiple When the [`multiple`](/en-US/docs/Web/HTML/Attributes/multiple) Boolean attribute is specified, the file input allows the user to select more than one file. ## Non-standard attributes In addition to the attributes listed above, the following non-standard attributes are available on some browsers. You should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don't implement them. ### `webkitdirectory` The Boolean `webkitdirectory` attribute, if present, indicates that only directories should be available to be selected by the user in the file picker interface. See {{domxref("HTMLInputElement.webkitdirectory")}} for additional details and examples. Though originally implemented only for WebKit-based browsers, `webkitdirectory` is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative. ## 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 a string containing one or more of these unique file type specifiers as its value, 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, 90)}} > **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. ### Getting information on selected files The selected files' are returned by the element's `HTMLInputElement.files` property, which is a {{domxref("FileList")}} object containing a list of {{domxref("File")}} objects. The `FileList` behaves like an array, so you can check its `length` property to get the number of selected files. Each `File` object contains the following information: - `name` - : The file's name. - `lastModified` - : A number specifying the date and time at which the file was last modified, in milliseconds since the UNIX epoch (January 1, 1970, at midnight). - `lastModifiedDate` {{deprecated_inline}} - : A {{jsxref("Date")}} object representing the date and time at which the file was last modified. _This is deprecated and should not be used. Use `lastModified` instead._ - `size` - : The size of the file in bytes. - `type` - : The file's [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). - `webkitRelativePath` {{non-standard_inline}} - : A string specifying the file's path relative to the base directory selected in a directory picker (that is, a `file` picker in which the [`webkitdirectory`](#webkitdirectory) attribute is set). _This is non-standard and should be used with caution._ > **Note:** You can set as well as get the value of `HTMLInputElement.files` in all modern browsers; this was most recently added to Firefox, in version 57 (see [Firefox bug 1384030](https://bugzil.la/1384030)). ### 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`](#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; } ``` This produces a similar-looking output to the previous example: {{EmbedLiveSample('Limiting_accepted_file_types', 650, 90)}} > **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/file-with-accept.html), and also [see it running live](https://mdn.github.io/learning-area/html/forms/file-examples/file-with-accept.html). It may look similar, but if you try selecting a file with this input, you'll see that the file picker only lets you select the file types specified in the `accept` value (the exact interface differs across browsers and operating systems). 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 the `accept` attribute is backed up by appropriate server-side validation. ### Detecting cancellations The `cancel` event is fired when the user does not change their selection, reselecting the previously selected files. The `cancel` event is also fired when the file picker dialog gets closed, or canceled, via the "cancel" button or the <kbd>escape</kbd> key. For example, the following code will log to the console if the user closes the popup without selecting a file: ```js const elem = document.createElement("input"); elem.type = "file"; elem.addEventListener("cancel", () => { console.log("Cancelled."); }); elem.addEventListener("change", () => { if (elem.files.length == 1) { console.log("File selected: ", elem.files[0]); } }); elem.click(); ``` ### Notes 1. You cannot set the value of a file picker from a script — doing something like the following has no effect: ```js const input = document.querySelector("input[type=file]"); input.value = "foo"; ``` 2. When a file is chosen using an `<input type="file">`, the real path to the source file is not shown in the input's `value` attribute for obvious security reasons. Instead, the filename is shown, with `C:\fakepath\` prepended to it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is [defined in the spec](https://html.spec.whatwg.org/multipage/forms.html#fakepath-srsly). ## Examples In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the `HTMLInputElement.files` property, as well as showing off a few clever tricks. > **Note:** You can see the complete source code for this example on GitHub — [file-example.html](https://github.com/mdn/learning-area/blob/main/html/forms/file-examples/file-example.html) ([see it live also](https://mdn.github.io/learning-area/html/forms/file-examples/file-example.html)). We won't explain the CSS; the JavaScript is the main focus. First of all, let's look at the HTML: ```html <form method="post" enctype="multipart/form-data"> <div> <label for="image_uploads">Choose images to upload (PNG, JPG)</label> <input type="file" id="image_uploads" name="image_uploads" accept=".jpg, .jpeg, .png" multiple /> </div> <div class="preview"> <p>No files currently selected for upload</p> </div> <div> <button>Submit</button> </div> </form> ``` ```css hidden html { font-family: sans-serif; } form { background: #ccc; margin: 0 auto; padding: 20px; border: 1px solid black; } form ol { padding-left: 0; } form li, div > p { background: #eee; display: flex; justify-content: space-between; margin-bottom: 10px; list-style-type: none; border: 1px solid black; } form img { height: 64px; order: 1; } form p { line-height: 32px; padding-left: 10px; } form label, form button { background-color: #7f9ccb; padding: 5px 10px; border-radius: 5px; border: 1px ridge black; font-size: 0.8rem; height: auto; } form label:hover, form button:hover { background-color: #2d5ba3; color: white; } form label:active, form button:active { background-color: #0d3f8f; color: white; } ``` This is similar to what we've seen before — nothing special to comment on. Next, let's walk through the JavaScript. In the first lines of script, we get references to the form input itself, and the {{htmlelement("div")}} element with the class of `.preview`. Next, we hide the {{htmlelement("input")}} element — we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. You can activate the `input` element by clicking its {{htmlelement("label")}}, so it is better to visually hide the `input` and style the label like a button, so the user will know to interact with it if they want to upload files. ```js const input = document.querySelector("input"); const preview = document.querySelector(".preview"); input.style.opacity = 0; ``` > **Note:** {{cssxref("opacity")}} is used to hide the file input instead of {{cssxref("visibility", "visibility: hidden")}} or {{cssxref("display", "display: none")}}, because assistive technology interprets the latter two styles to mean the file input isn't interactive. Next, we add an [event listener](/en-US/docs/Web/API/EventTarget/addEventListener) to the input to listen for changes to its selected value (in this case, when files are selected). The event listener invokes our custom `updateImageDisplay()` function. ```js input.addEventListener("change", updateImageDisplay); ``` Whenever the `updateImageDisplay()` function is invoked, we: - Use a {{jsxref("Statements/while", "while")}} loop to empty the previous contents of the preview `<div>`. - Grab the {{domxref("FileList")}} object that contains the information on all the selected files, and store it in a variable called `curFiles`. - Check to see if no files were selected, by checking if `curFiles.length` is equal to 0. If so, print a message into the preview `<div>` stating that no files have been selected. - If files _have_ been selected, we loop through each one, printing information about it into the preview `<div>`. Things to note here: - We use the custom `validFileType()` function to check whether the file is of the correct type (e.g. the image types specified in the `accept` attribute). - If it is, we: - Print out its name and file size into a list item inside the previous `<div>` (obtained from `file.name` and `file.size`). The custom `returnFileSize()` function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes). - Generate a thumbnail preview of the image by calling {{domxref("URL/createObjectURL_static", "URL.createObjectURL(file)")}}. Then, insert the image into the list item too by creating a new {{htmlelement("img")}} and setting its [`src`](/en-US/docs/Web/HTML/Element/img#src) to the thumbnail. - If the file type is invalid, we display a message inside a list item telling the user that they need to select a different file type. ```js function updateImageDisplay() { while (preview.firstChild) { preview.removeChild(preview.firstChild); } const curFiles = input.files; if (curFiles.length === 0) { const para = document.createElement("p"); para.textContent = "No files currently selected for upload"; preview.appendChild(para); } else { const list = document.createElement("ol"); preview.appendChild(list); for (const file of curFiles) { const listItem = document.createElement("li"); const para = document.createElement("p"); if (validFileType(file)) { para.textContent = `File name ${file.name}, file size ${returnFileSize( file.size, )}.`; const image = document.createElement("img"); image.src = URL.createObjectURL(file); image.alt = image.title = file.name; listItem.appendChild(image); listItem.appendChild(para); } else { para.textContent = `File name ${file.name}: Not a valid file type. Update your selection.`; listItem.appendChild(para); } list.appendChild(listItem); } } } ``` The custom `validFileType()` function takes a {{domxref("File")}} object as a parameter, then uses {{jsxref("Array.prototype.includes()")}} to check if any value in the `fileTypes` matches the file's `type` property. If a match is found, the function returns `true`. If no match is found, it returns `false`. ```js // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types const fileTypes = [ "image/apng", "image/bmp", "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/svg+xml", "image/tiff", "image/webp", "image/x-icon", ]; function validFileType(file) { return fileTypes.includes(file.type); } ``` The `returnFileSize()` function takes a number (of bytes, taken from the current file's `size` property), and turns it into a nicely formatted size in bytes/KB/MB. ```js function returnFileSize(number) { if (number < 1024) { return `${number} bytes`; } else if (number >= 1024 && number < 1048576) { return `${(number / 1024).toFixed(1)} KB`; } else if (number >= 1048576) { return `${(number / 1048576).toFixed(1)} MB`; } } ``` ```js hidden const button = document.querySelector("form button"); button.addEventListener("click", (e) => { e.preventDefault(); const para = document.createElement("p"); para.append("Image uploaded!"); preview.replaceChildren(para); }); ``` The example looks like this; have a play: {{EmbedLiveSample('Examples', '100%', 200)}} ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing the path to the selected file. </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}}, {{domxref("Element/input_event", "input")}} and {{domxref("HTMLElement/cancel_event", "cancel")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td><a href="/en-US/docs/Web/HTML/Element/input#required"><code>required</code></a></td> </tr> <tr> <td><strong>Additional Attributes</strong></td> <td> <a href="#accept" aria-current="page"><code>accept</code></a>, <a href="#capture" aria-current="page"><code>capture</code></a>, <a href="#multiple" aria-current="page"><code>multiple</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>files</code> and <code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications) — contains a number of other useful examples related to `<input type="file">` and the [File API](/en-US/docs/Web/API/File). - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/week/index.md
--- title: <input type="week"> slug: Web/HTML/Element/input/week page-type: html-element browser-compat: html.elements.input.type_week --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`week`** create input fields allowing easy entry of a year plus the [ISO 8601 week number](https://en.wikipedia.org/wiki/ISO_8601#Week_dates) during that year (i.e., week 1 to [52 or 53](https://en.wikipedia.org/wiki/ISO_8601#Week_dates)). {{EmbedInteractiveExample("pages/tabbed/input-week.html", "tabbed-shorter")}} The control's user interface varies from browser to browser; cross-browser support is currently a bit limited, with only Chrome/Opera and Microsoft Edge supporting it at this time. In non-supporting browsers, the control degrades gracefully to function identically to [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text). ![An input reading 'week 01, 2017'. The background of the 2017 is the same blue as the focus ring. There are 3 icons in the input: x or clear, a spinner with small up and down arrows, and a larger down arrow. A calendar is a pop-up below the input set to January 2017. The first column of the calendar is the week: 52, 1, 2, 3, 4, 5. the full month calendar is to the right of that. The row with Week 1 and January 2 to 8 is highlighted. On the same line as the month, there are buttons to move right and left for the next and previous months.](week-control-chrome.png) ## Value A string representing the value of the week/year entered into the input. The format of the date and time value used by this input type is described in [Week strings](/en-US/docs/Web/HTML/Date_and_time_formats#week_strings). You can set a default value for the input by including a value inside the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute, like so: ```html <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" value="2017-W01" /> ``` {{EmbedLiveSample('Value', 600, 60)}} One thing to note is that the displayed format may differ from the actual `value`, which is always formatted `yyyy-Www`. When the above value is submitted to the server, for example, browsers may display it as `Week 01, 2017`, but the submitted value will always look like `week=2017-W01`. You can also get and set the value in JavaScript using the input element's {{domxref("HTMLInputElement.value", "value")}} property, for example: ```js const weekControl = document.querySelector('input[type="week"]'); weekControl.value = "2017-W45"; ``` ## Additional attributes In addition to the attributes common to {{HTMLElement("input")}} elements, week inputs offer the following attributes. ### max The latest (time-wise) year and week number, in the string format discussed in the [Value](#value) section above, to accept. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) entered into the element exceeds this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If the value of the `max` attribute isn't a valid week string, then the element has no maximum value. This value must be greater than or equal to the year and week specified by the `min` attribute. ### min The earliest year and week to accept. If the [`value`](/en-US/docs/Web/HTML/Element/input#value) of the element is less than this, the element fails [constraint validation](/en-US/docs/Web/HTML/Constraint_validation). If a value is specified for `min` that isn't a valid week string, the input has no minimum value. This value must be less than or equal to the value of the `max` attribute. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `week` inputs, the value of `step` is given in weeks, with a scaling factor of 604,800,000 (since the underlying numeric value is in milliseconds). The default value of `step` is 1, indicating 1week. The default stepping base is -259,200,000, which is the beginning of the first week of 1970 (`"1970-W01"`). _At this time, it's unclear what a value of `"any"` means for `step` when used with `week` inputs. This will be updated as soon as that information is determined._ ## Using week inputs Week inputs sound convenient at first glance, since they provide an easy UI for choosing weeks, and they normalize the data format sent to the server, regardless of the user's browser or locale. However, there are issues with `<input type="week">` because browser support is not guaranteed across all browsers. We'll look at basic and more complex uses of `<input type="week">`, then offer advice on mitigating the browser support issue later on (see [Handling browser support](#handling_browser_support)). ### Basic uses of week The simplest use of `<input type="week">` involves a basic `<input>` and {{htmlelement("label")}} element combination, as seen below: ```html <form> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" /> </form> ``` {{EmbedLiveSample('Basic_uses_of_week', 600, 40)}} ### Controlling input size `<input type="week">` doesn't support form sizing attributes such as [`size`](/en-US/docs/Web/HTML/Element/input#size). You'll have to resort to [CSS](/en-US/docs/Web/CSS) for sizing needs. ### Using the step attribute You should be able to use the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute to vary the number of weeks jumped whenever they are incremented or decremented, however it doesn't seem to have any effect on supporting browsers. ## Validation By default, `<input type="week">` does not apply any validation to entered values. The UI implementations generally don't let you specify anything that isn't a valid week/year, which is helpful, but it's still possible to submit with the field empty, and you might want to restrict the range of choosable weeks. ### Setting maximum and minimum weeks You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to restrict the valid weeks that can be chosen by the user. In the following example we are setting a minimum value of `Week 01, 2017` and a maximum value of `Week 52, 2017`: ```html <form> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" min="2017-W01" max="2017-W52" /> <span class="validity"></span> </form> ``` {{EmbedLiveSample('Setting_maximum_and_minimum_weeks', 600, 40)}} Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether the current value is valid. We had to put the icons on a {{htmlelement("span")}} next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ```css div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` The result here is that only weeks between W01 and W52 in 2017 will be seen as valid and be selectable in supporting browsers. ### Making week values required In addition you can use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute to make filling in the week mandatory. As a result, supporting browsers will display an error if you try to submit an empty week field. Let's look at an example; here we've set minimum and maximum weeks, and also made the field required: ```html <form> <div> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" min="2017-W01" max="2017-W52" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try to submit the form with no value, the browser displays an error. Try playing with the example now: {{EmbedLiveSample('Making_week_values_required', 600, 120)}} Here is a screenshot for those of you who aren't using a supporting browser: ![The week form control has two dashes where the week number should be. A popup with a yellow warning symbol and a 'Please fill out this field' is emanating from the two dashes, which are highlighted in blue, the same blue as the input's focus ring.](week-validation-chrome.png) > **Warning:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). ## Handling browser support As mentioned above, the major problem with using week inputs right now is browser support: Safari and Firefox don't support it on desktop, and old versions of IE don't support it. Mobile platforms such as Android and iOS make perfect use of such input types, providing specialist UI controls that make it really easy to select values in a touchscreen environment. For example, the `week` picker on Chrome for Android looks like this: ![A modal popup. The header reads 'set week'. There are two columns: the left has 36 in the middle at full opacity, with 35 above it and 37 below being semi-opaque. On the right side, 2017 is fully opaque. There are no other options. Three text links or buttons on the bottom include 'clear' on the 'left' and 'cancel' and 'set' on the right.](week-chrome-android.png) Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the more serious. As mentioned earlier, with a `week` input the actual value is always normalized to the format `yyyy-Www`. When the browser falls back to a generic text input, there's nothing to guide the user toward correctly formatting the input (and it's certainly not intuitive). There are multiple ways in which people could write week values; for example: - `Week 1 2017` - `Jan 2-8 2017` - `2017-W01` - etc. The best way to deal with week/years in forms in a cross-browser way at the moment is to get the user to enter the week number and year in separate controls ({{htmlelement("select")}} elements being popular; see below for an example), or use JavaScript libraries such as [jQuery date picker](https://jqueryui.com/datepicker/). ## Examples In this example we create two sets of UI elements for choosing weeks: a native picker created using `<input type="week">`, and a set of two {{htmlelement("select")}} elements for choosing weeks/years in older browsers that don't support the `week` input type. {{EmbedLiveSample('Examples', 600, 140)}} The HTML looks like so: ```html <form> <div class="nativeWeekPicker"> <label for="week">What week would you like to start?</label> <input id="week" type="week" name="week" min="2017-W01" max="2018-W52" required /> <span class="validity"></span> </div> <p class="fallbackLabel">What week would you like to start?</p> <div class="fallbackWeekPicker"> <div> <span> <label for="week">Week:</label> <select id="fallbackWeek" name="week"></select> </span> <span> <label for="year">Year:</label> <select id="year" name="year"> <option value="2017" selected>2017</option> <option value="2018">2018</option> </select> </span> </div> </div> </form> ``` The week values are dynamically generated by the JavaScript code below. ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` The other part of the code that may be of interest is the feature detection code. To detect whether the browser supports `<input type="week">`, we create a new {{htmlelement("input")}} element, try setting its `type` to `week`, then immediately check what its `type` is set to. Non-supporting browsers will return `text`, because the `week` type falls back to type `text`. If `<input type="week">` is not supported, we hide the native picker and show the fallback picker UI ({{htmlelement("select")}}s) instead. ```js // Get UI elements const nativePicker = document.querySelector(".nativeWeekPicker"); const fallbackPicker = document.querySelector(".fallbackWeekPicker"); const fallbackLabel = document.querySelector(".fallbackLabel"); const yearSelect = document.querySelector("#year"); const weekSelect = document.querySelector("#fallbackWeek"); // Hide fallback initially fallbackPicker.style.display = "none"; fallbackLabel.style.display = "none"; // Test whether a new date input falls back to a text input or not const test = document.createElement("input"); try { test.type = "week"; } catch (e) { console.log(e.description); } // If it does, run the code inside the if () {} block if (test.type === "text") { // Hide the native picker and show the fallback nativePicker.style.display = "none"; fallbackPicker.style.display = "block"; fallbackLabel.style.display = "block"; // populate the weeks dynamically populateWeeks(); } function populateWeeks() { // Populate the week select with 52 weeks for (let i = 1; i <= 52; i++) { const option = document.createElement("option"); option.textContent = i < 10 ? `0${i}` : i; weekSelect.appendChild(option); } } ``` > **Note:** Remember that some years have 53 weeks in them (see [Weeks per year](https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year))! You'll need to take this into consideration when developing production apps. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing a week and year, or empty </td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#step"><code>step</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>value</code>, <code>valueAsDate</code>, <code>valueAsNumber</code>, and <code>list</code>. </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, and {{domxref("HTMLInputElement.stepUp", "stepUp()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}} - [Date and time formats used in HTML](/en-US/docs/Web/HTML/Date_and_time_formats) - [`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local), [`<input type="date">`](/en-US/docs/Web/HTML/Element/input/date), [`<input type="time">`](/en-US/docs/Web/HTML/Element/input/time), and [`<input type="month">`](/en-US/docs/Web/HTML/Element/input/month) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/submit/index.md
--- title: <input type="submit"> slug: Web/HTML/Element/input/submit page-type: html-element browser-compat: html.elements.input.type_submit --- {{HTMLSidebar}} {{HTMLElement("input")}} elements of type **`submit`** are rendered as buttons. When the {{domxref("Element/click_event", "click")}} event occurs (typically because the user clicked the button), the {{Glossary("user agent")}} attempts to submit the form to the server. ## Value An `<input type="submit">` element's [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute contains a string which is displayed as the button's label. Buttons do not have a true value otherwise. The `value` provides the {{glossary("accessible description")}} for the button. ### Setting the value attribute ```html <input type="submit" value="Send Request" /> ``` {{EmbedLiveSample("Setting_the_value_attribute", 650, 30)}} ### Omitting the value attribute If you don't specify a `value`, the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here's an example of a submit button with a default label in your browser: ```html <input type="submit" /> ``` {{EmbedLiveSample("Omitting_the_value_attribute", 650, 30)}} ## Additional attributes In addition to the attributes shared by all {{HTMLElement("input")}} elements, `submit` button inputs support the following attributes. ### formaction A string indicating the URL to which to submit the data. This takes precedence over the [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute on the {{HTMLElement("form")}} element that owns the {{HTMLElement("input")}}. This attribute is also available on [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) and {{HTMLElement("button")}} elements. ### formenctype A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values: - `application/x-www-form-urlencoded` - : This, the default value, sends the form data as a string after [URL encoding](https://en.wikipedia.org/wiki/URL_encoding) the text using an algorithm such as {{jsxref("encodeURI", "encodeURI()")}}. - `multipart/form-data` - : Uses the {{domxref("FormData")}} API to manage the data, allowing for files to be submitted to the server. You _must_ use this encoding type if your form includes any {{HTMLElement("input")}} elements of [`type`](/en-US/docs/Web/HTML/Element/input#type) `file` ([`<input type="file">`](/en-US/docs/Web/HTML/Element/input/file)). - `text/plain` - : Plain text; mostly useful only for debugging, so you can easily see the data that's to be submitted. If specified, the value of the `formenctype` attribute overrides the owning form's [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute. This attribute is also available on [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) and {{HTMLElement("button")}} elements. ### formmethod A string indicating the HTTP method to use when submitting the form's data; this value overrides any [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute given on the owning form. Permitted values are: - `get` - : A URL is constructed by starting with the URL given by the `formaction` or [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by `formenctype` or the form's [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) attribute. This URL is then sent to the server using an HTTP {{HTTPMethod("get")}} request. This method works well for simple forms that contain only {{Glossary("ASCII")}} characters and have no side effects. This is the default value. - `post` - : The form's data is included in the body of the request that is sent to the URL given by the `formaction` or [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute using an HTTP {{HTTPMethod("post")}} method. This method supports complex data and file attachments. - `dialog` - : This method is used to indicate that the button closes the dialog with which the input is associated, and does not transmit the form data at all. This attribute is also available on [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) and {{HTMLElement("button")}} elements. ### formnovalidate A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute on the element's owning form. This attribute is also available on [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) and {{HTMLElement("button")}} elements. ### formtarget A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a **browsing context** (that is, a tab, window, or {{HTMLElement("iframe")}}). A value specified here overrides any target given by the [`target`](/en-US/docs/Web/HTML/Element/form#target) attribute on the {{HTMLElement("form")}} that owns this input. In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used: - `_self` - : Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. - `_blank` - : Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the {{Glossary("user agent")}}. - `_parent` - : Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as `_self`. - `_top` - : Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as `_self`. This attribute is also available on [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) and {{HTMLElement("button")}} elements. ## Using submit buttons `<input type="submit">` buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use [`<input type="button">`](/en-US/docs/Web/HTML/Element/input/button), or better still, a {{htmlelement("button")}} element. If you choose to use `<button>` elements to create the buttons in your form, keep this in mind: If the `<button>` is inside a {{HTMLElement("form")}}, that button will be treated as the "submit" button. So you should be in the habit of expressly specifying which button is the submit button. ### A simple submit button We'll begin by creating a form with a simple submit button: ```html <form> <div> <label for="example">Let's submit some text</label> <input id="example" type="text" name="text" /> </div> <div> <input type="submit" value="Send" /> </div> </form> ``` This renders like so: {{EmbedLiveSample("A_simple_submit_button", 650, 100)}} Try entering some text into the text field, and then submitting the form. Upon submitting, the data name/value pair gets sent to the server. In this instance, the string will be `text=usertext`, where "usertext" is the text entered by the user, encoded to preserve special characters. Where and how the data is submitted depends on the configuration of the `<form>`; see [Sending form data](/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data) for more details. ### Adding a keyboard shortcut to a submit button Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a submit button — just as you would with any {{HTMLElement("input")}} for which it makes sense — you use the [`accesskey`](/en-US/docs/Web/HTML/Global_attributes/accesskey) global attribute. In this example, <kbd>s</kbd> is specified as the access key (you'll need to press <kbd>s</kbd> plus the particular modifier keys for your browser/OS combination). In order to avoid conflicts with the user agent's own keyboard shortcuts, different modifier keys are used for access keys than for other shortcuts on the host computer. See [`accesskey`](/en-US/docs/Web/HTML/Global_attributes/accesskey) for further details. Here's the previous example with the <kbd>s</kbd> access key added: ```html <form> <div> <label for="example">Let's submit some text</label> <input id="example" type="text" name="text" /> </div> <div> <input type="submit" value="Send" accesskey="s" /> </div> </form> ``` For example, in Firefox for Mac, pressing <kbd>Control</kbd>-<kbd>Option</kbd>-<kbd>S</kbd> triggers the Send button, while Chrome on Windows uses <kbd>Alt</kbd>+<kbd>S</kbd>. {{EmbedLiveSample("Adding_a_keyboard_shortcut_to_a_submit_button", 650, 100)}} The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the [`title`](/en-US/docs/Web/HTML/Global_attributes/title) attribute) can also help, although it's not a complete solution for accessibility purposes. ### Disabling and enabling a submit button To disable a submit button, specify the [`disabled`](/en-US/docs/Web/HTML/Attributes/disabled) attribute on it, like so: ```html <input type="submit" value="Send" disabled /> ``` You can enable and disable buttons at run time by setting `disabled` to `true` or `false`; in JavaScript this looks like `btn.disabled = true` or `btn.disabled = false`. > **Note:** See the [`<input type="button">`](/en-US/docs/Web/HTML/Element/input/button#disabling_and_enabling_a_button) page for more ideas about enabling and disabling buttons. ## Validation Submit buttons don't participate in constraint validation; they have no real value to be constrained. ## Examples We've included simple examples above. There isn't really anything more to say about submit buttons. There's a reason this kind of control is sometimes called a "simple button." ## Technical Summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>A string used as the button's label</td> </tr> <tr> <td><strong>Events</strong></td> <td>{{domxref("Element/click_event", "click")}}</td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#type"><code>type</code></a> and <a href="/en-US/docs/Web/HTML/Element/input#value"><code>value</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td>None</td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role"><code>button</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface which implements it. - [Forms and buttons](/en-US/docs/Learn/Forms/Basic_native_form_controls#actual_buttons) - [HTML forms](/en-US/docs/Learn/Forms) - The {{HTMLElement("button")}} element - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/time/index.md
--- title: <input type="time"> slug: Web/HTML/Element/input/time page-type: html-element browser-compat: html.elements.input.type_time --- {{HTMLSidebar}} {{htmlelement("input")}} elements of type **`time`** create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds). The control's user interface varies from browser to browser; see [Browser compatibility](#browser_compatibility) for further details. In unsupported browsers, the control degrades gracefully to [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text). {{EmbedInteractiveExample("pages/tabbed/input-time.html", "tabbed-standard")}} ## Appearance ### Chrome and Opera In Chrome/Opera the `time` control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. In some versions, an "X" button is provided to clear the control's value. ![12-hour Chrome time input](chrome_time.png) 12-hour ![24-hour Chrome time input](chrome-time.png) 24-hour ### Firefox Firefox's `time` control is very similar to Chrome's, except that it doesn't have the up and down arrows. It also uses a 12- or 24-hour format for inputting times, based on system locale. An "X" button is provided to clear the control's value. ![12-hour Firefox time input](firefox-time.png) 12-hour ![24-hour Firefox time input](firefox-time-24.png) 24-hour ### Edge The Edge `time` control is somewhat more elaborate, opening up an hour and minute picker with sliding reels. It, like Chrome, uses a 12- or 24-hour format for inputting times, based on system locale: ![12-hour Edge time input](edge_time.png) 12-hour ![24-hour Edge time input](edge-time.png) 24-hour ## Value A string containing the value of the time entered into the input. ### Setting the value attribute You can set a default value for the input by including a valid time in the [`value`](/en-US/docs/Web/HTML/Element/input#value) attribute when creating the `<input>` element, like so: ```html <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30" /> ``` {{ EmbedLiveSample('Setting_the_value_attribute', 600, 60) }} ### Setting the value using JavaScript You can also get and set the time value in JavaScript using the {{domxref("HTMLInputElement")}} `value` property, for example: ```js const timeControl = document.querySelector('input[type="time"]'); timeControl.value = "15:30"; ``` ### Time value format The `value` of the `time` input is always in 24-hour format that includes leading zeros: `hh:mm`, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent). If the time includes seconds (see [Using the step attribute](#using_the_step_attribute)), the format is always `hh:mm:ss`. You can learn more about the format of the time value used by this input type in [Time strings](/en-US/docs/Web/HTML/Date_and_time_formats#time_strings). In this example, you can see the time input's value by entering a time and seeing how it changes afterward. First, a look at the HTML. This is simple enough, with the label and input as we've seen before, but with the addition of a {{HTMLElement("p")}} element with a {{HTMLElement("span")}} to display the value of the `time` input: ```html <form> <label for="startTime">Start time: </label> <input type="time" id="startTime" /> <p> Value of the <code>time</code> input: <code> "<span id="value">n/a</span>"</code>. </p> </form> ``` The JavaScript code adds code to the time input to watch for the {{domxref("Element/input_event", "input")}} event, which is triggered every time the contents of an input element change. When this happens, the contents of the `<span>` are replaced with the new value of the input element. ```js const startTime = document.getElementById("startTime"); const valueSpan = document.getElementById("value"); startTime.addEventListener( "input", () => { valueSpan.innerText = startTime.value; }, false, ); ``` {{EmbedLiveSample("Time_value_format", 600, 80)}} When a form including a `time` input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form `name=hh%3Amm`, or `name=hh%3Amm%3Ass` if seconds are included (see [Using the step attribute](#using_the_step_attribute)). ## Additional attributes In addition to the attributes common to all {{HTMLElement("input")}} elements, `time` inputs offer the following attributes. > **Note:** Unlike many data types, time values have a **periodic domain**, meaning that the values reach the highest possible value, then wrap back around to the beginning again. For example, specifying a `min` of `14:00` and a `max` of `2:00` means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM. See more in the [making min and max cross midnight](#making_min_and_max_cross_midnight) section of this article. ### list The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The {{HTMLElement("datalist")}} provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the [`type`](/en-US/docs/Web/HTML/Element/input#type) are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ### max A string indicating the latest time to accept, specified in the same [time value format](#time_value_format) as described above. If the specified string isn't a valid time, no maximum value is set. ### min A string specifying the earliest time to accept, given in the [time value format](#time_value_format) described previously. If the value specified isn't a valid time string, no minimum value is set. ### readonly A Boolean attribute which, if present, means this field cannot be edited by the user. Its `value` can, however, still be changed by JavaScript code directly setting the {{domxref("HTMLInputElement")}} `value` property. > **Note:** Because a read-only field cannot have a value, `required` does not have any effect on inputs with the `readonly` attribute also specified. ### step The `step` attribute is a number that specifies the granularity that the value must adhere to, or the special value `any`, which is described below. Only values which are equal to the basis for stepping ([`min`](#min) if specified, [`value`](/en-US/docs/Web/HTML/Element/input#value) otherwise, and an appropriate default value if neither of those is provided) are valid. A string value of `any` means that no stepping is implied, and any value is allowed (barring other constraints, such as [`min`](#min) and [`max`](#max)). > **Note:** When the data entered by the user doesn't adhere to the stepping configuration, the {{Glossary("user agent")}} may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. For `time` inputs, the value of `step` is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of `step` is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds). _At this time, it's unclear what a value of `any` means for `step` when used with `time` inputs. This will be updated as soon as that information is determined._ ## Using time inputs ### Basic uses of time The simplest use of `<input type="time">` involves a basic `<input>` and {{htmlelement("label")}} element combination, as seen below: ```html <form> <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" /> </form> ``` {{EmbedLiveSample('Basic_uses_of_time', 600, 40)}} ### Controlling input size `<input type="time">` doesn't support form sizing attributes such as [`size`](/en-US/docs/Web/HTML/Element/input#size), since times are always about the same number of characters long. You'll have to resort to [CSS](/en-US/docs/Web/CSS) for sizing needs. ### Using the step attribute You can use the [`step`](/en-US/docs/Web/HTML/Element/input#step) attribute to vary the amount of time jumped whenever the time is incremented or decremented (for example, so the time moves by 10 minutes at a time when clicking the little arrow widgets). > **Note:** This property has some strange effects across browsers, so is not completely reliable. It takes an integer value that equates to the number of seconds you want to increment by; the default value is 60 seconds, or one minute. If you specify a value of less than 60 seconds (1 minute), the `time` input will show a seconds input area alongside the hours and minutes: ```html <form> <label for="appt-time">Choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" step="2" /> </form> ``` {{EmbedLiveSample('Using_the_step_attribute', 600, 40)}} In Chrome and Opera, which are the only browsers to show up/down iteration arrows, clicking the arrows changes the seconds value by two seconds, but doesn't affect the hours or minutes. Minutes (or hours) can only be used for stepping when you specify a number of minutes (or hours) in seconds, such as 120 for 2 minutes, or 7200 for 2 hours). In Firefox, there are no arrows, so the `step` value isn't used. However, providing it _does_ add the seconds input area adjacent to the minutes section. The steps value seems to have no effect in Edge. > **Note:** Using `step` seems to cause validation to not work properly (as seen in the next section). ## Validation By default, `<input type="time">` does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value. This is helpful (assuming the `time` input is fully supported by the user agent), but you can't entirely rely on the value to be a proper time string, since it might be an empty string (`""`), which is allowed. It's also possible for the value to look roughly like a valid time but not be correct, such as `25:05`. ### Setting maximum and minimum times You can use the [`min`](/en-US/docs/Web/HTML/Element/input#min) and [`max`](/en-US/docs/Web/HTML/Element/input#max) attributes to restrict the valid times that can be chosen by the user. In the following example we are setting a minimum time of `12:00` and a maximum time of `18:00`: ```html <form> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" /> <span class="validity"></span> </form> ``` {{ EmbedLiveSample('Setting_maximum_and_minimum_times', 600, 40) }} Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether the current value is valid. We had to put the icons on a {{htmlelement("span")}} next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively. ```css div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` The result here is that: - Only times between 12:00 and 18:00 will be seen as valid; times outside that range will be denoted as invalid. - Depending on what browser you're using, you might find that times outside the specified range might not even be selectable in the time picker (e.g. Edge). #### Making min and max cross midnight By setting a [`min`](/en-US/docs/Web/HTML/Element/input#min) attribute greater than the [`max`](/en-US/docs/Web/HTML/Element/input#max) attribute, the valid time range will wrap around midnight to produce a valid time range which crosses midnight. This functionality is not supported by any other input types. While this feature is [in the HTML spec](https://html.spec.whatwg.org/multipage/input.html#has-a-reversed-range), it is not yet universally supported. Chrome-based browsers support it starting in version 82 and Firefox added it in version 76. Safari as of version 14.1 does not support this. Be prepared for this situation to arise: ```js const input = document.createElement("input"); input.type = "time"; input.min = "23:00"; input.max = "01:00"; input.value = "23:59"; if (input.validity.valid && input.type === "time") { // <input type=time> reversed range supported } else { // <input type=time> reversed range unsupported } ``` ### Making times required In addition, you can use the [`required`](/en-US/docs/Web/HTML/Element/input#required) attribute to make filling in the time mandatory. As a result, supporting browsers will display an error if you try to submit a time that is outside the set bounds, or an empty time field. Let's look at an example; here we've set minimum and maximum times, and also made the field required: ```html <form> <div> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` If you try to submit the form with an incomplete time (or with a time outside the set bounds), the browser displays an error. Try playing with the example now: {{ EmbedLiveSample('Making_times_required', 600, 120) }} > **Warning:** HTML form validation is _not_ a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). ## Handling browser support As mentioned, older versions of Safari and a few other, less common, browsers don't support time inputs natively. In general, otherwise, support is good — especially on mobile platforms, which tend to have very nice user interfaces for specifying a time value. For example, the `time` picker on Chrome for Android looks like this: ![Phone screen showing modal dialog with 10:21 as a header. The 10 is fully opaque. The 21 is not. The main area has a circle with the numbers 1 - 12 in a ring, and the number 13 -24 on an inner ring. The number 10 is highlighted with a blue circle. The buttons at the bottom are clear, cancel, and set.](chrome-android-time.png) Browsers that don't support time inputs gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling. The second problem is the more serious; as mentioned previously, `time` inputs' values are always normalized to the format `hh:mm` or `hh:mm:ss`. With a text input, on the other hand, by default the browser has no idea of what format the time should be in, and there are multiple ways in which people write times, such as: - `3.00 pm` - `3:00pm` - `15:00` - `3 o'clock in the afternoon` - etc. One way around this is to put a [`pattern`](/en-US/docs/Web/HTML/Element/input#pattern) attribute on your `time` input. Even though the `time` input doesn't use it, the `text` input fallback will. For example, try viewing the following demo in a browser that doesn't support time inputs: ```html <form> <div> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required pattern="[0-9]{2}:[0-9]{2}" /> <span class="validity"></span> </div> <div> <input type="submit" value="Submit form" /> </div> </form> ``` {{ EmbedLiveSample('Handling_browser_support', 600, 100) }} If you try submitting it, you'll see that non-supporting browsers now display an error message (and highlight the input as invalid) if your entry doesn't match the pattern `nn:nn`, where `n` is a number from 0 to 9. Of course, this doesn't stop people from entering invalid times, or incorrectly formatted times that follow the pattern. Then there's the problem of the user having no idea exactly what format the time is expected to be in. ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` The best way to deal with times in forms in a cross-browser way, for the time being, is to get the user to enter the hours and minutes (and seconds if required) in separate controls ({{htmlelement("select")}} elements are popular; see below for an example), or use JavaScript libraries such as the [jQuery timepicker plugin](https://timepicker.co/). ## Examples In this example, we create two sets of interface elements for choosing times: a native picker created with `<input type="time">`, and a set of two {{htmlelement("select")}} elements for choosing hours/minutes in older browsers that don't support the native input. {{ EmbedLiveSample('Examples', 600, 140) }} The HTML looks like so: ```html <form> <div class="nativeTimePicker"> <label for="appt-time"> Choose an appointment time (opening hours 12:00 to 18:00): </label> <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" required /> <span class="validity"></span> </div> <p class="fallbackLabel"> Choose an appointment time (opening hours 12:00 to 18:00): </p> <div class="fallbackTimePicker"> <div> <span> <label for="hour">Hour:</label> <select id="hour" name="hour"></select> </span> <span> <label for="minute">Minute:</label> <select id="minute" name="minute"></select> </span> </div> </div> </form> ``` The hour and minutes values for their `<select>` elements are dynamically generated. ```css hidden div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } 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; } ``` The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports `<input type="time">`, we create a new {{htmlelement("input")}} element, try setting its `type` to `time`, then immediately check what its type is set to — non-supporting browsers will return `text`, because the `time` type falls back to type `text`. If `<input type="time">` is not supported, we hide the native picker and show the fallback picker UI ({{htmlelement("select")}}s) instead. ```js // Define variables const nativePicker = document.querySelector(".nativeTimePicker"); const fallbackPicker = document.querySelector(".fallbackTimePicker"); const fallbackLabel = document.querySelector(".fallbackLabel"); const hourSelect = document.querySelector("#hour"); const minuteSelect = document.querySelector("#minute"); // Hide fallback initially fallbackPicker.style.display = "none"; fallbackLabel.style.display = "none"; // Test whether a new time input falls back to a text input or not const test = document.createElement("input"); try { test.type = "time"; } catch (e) { console.log(e.description); } // If it does, run the code inside the if () {} block if (test.type === "text") { // Hide the native picker and show the fallback nativePicker.style.display = "none"; fallbackPicker.style.display = "block"; fallbackLabel.style.display = "block"; // Populate the hours and minutes dynamically populateHours(); populateMinutes(); } function populateHours() { // Populate the hours <select> with the 6 open hours of the day for (let i = 12; i <= 18; i++) { const option = document.createElement("option"); option.textContent = i; hourSelect.appendChild(option); } } function populateMinutes() { // populate the minutes <select> with the 60 hours of each minute for (let i = 0; i <= 59; i++) { const option = document.createElement("option"); option.textContent = i < 10 ? `0${i}` : i; minuteSelect.appendChild(option); } } // make it so that if the hour is 18, the minutes value is set to 00 // — you can't select times past 18:00 function setMinutesToZero() { if (hourSelect.value === "18") { minuteSelect.value = "00"; } } hourSelect.onchange = setMinutesToZero; minuteSelect.onchange = setMinutesToZero; ``` ## Technical Summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td>A string representing a time, or empty.</td> </tr> <tr> <td><strong>Events</strong></td> <td> {{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}} </td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <a href="/en-US/docs/Web/HTML/Element/input#autocomplete"><code>autocomplete</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#list"><code>list</code></a>, <a href="/en-US/docs/Web/HTML/Element/input#readonly"><code>readonly</code></a>, and <a href="/en-US/docs/Web/HTML/Element/input#step"><code>step</code></a> </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td> <code>value</code>, <code>valueAsDate</code>, <code>valueAsNumber</code>, and <code>list</code>. </td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, and {{domxref("HTMLInputElement.stepUp", "stepUp()")}}. </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td><a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role"><code>no corresponding role</code></a></td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}} - [Date and time formats used in HTML](/en-US/docs/Web/HTML/Date_and_time_formats) - [Date and Time picker tutorial](/en-US/docs/Learn/Forms/Basic_native_form_controls#date_and_time_picker) - [`<input type="datetime-local">`](/en-US/docs/Web/HTML/Element/input/datetime-local), [`<input type="date">`](/en-US/docs/Web/HTML/Element/input/date), [`<input type="week">`](/en-US/docs/Web/HTML/Element/input/week), and [`<input type="month">`](/en-US/docs/Web/HTML/Element/input/month) - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element/input
data/mdn-content/files/en-us/web/html/element/input/radio/index.md
--- title: <input type="radio"> slug: Web/HTML/Element/input/radio page-type: html-element browser-compat: html.elements.input.type_radio --- {{HTMLSidebar}} {{htmlelement("input")}} elements of type **`radio`** are generally used in **radio groups**—collections of radio buttons describing a set of related options. Only one radio button in a given group can be selected at the same time. Radio buttons are typically rendered as small circles, which are filled or highlighted when selected. {{EmbedInteractiveExample("pages/tabbed/input-radio.html", "tabbed-standard")}} They are called radio buttons because they look and operate in a similar manner to the push buttons on old-fashioned radios, such as the one shown below. ![Shows what radio buttons looked like in the olden days.](old-radio.jpg) > **Note:** [Checkboxes](/en-US/docs/Web/HTML/Element/input/checkbox) are similar to radio buttons, but with an important distinction: radio buttons are designed for selecting one value out of a set, whereas checkboxes let you turn individual values on and off. Where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. ## Value The `value` attribute is a string containing the radio button's value. The value is never shown to the user by their {{Glossary("user agent")}}. Instead, it's used to identify which radio button in a group is selected. ### Defining a radio group A radio group is defined by giving each of radio buttons in the group the same [`name`](/en-US/docs/Web/HTML/Element/input#name). Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. You can have as many radio groups on a page as you like, as long as each has its own unique `name`. For example, if your form needs to ask the user for their preferred contact method, you might create three radio buttons, each with the `name` property set to `contact` but one with the value `email`, one with the value `phone`, and one with the value `mail`. The user never sees the `value` or the `name` (unless you expressly add code to display it). The resulting HTML looks like this: ```html <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> ``` Here you see the three radio buttons, each with the `name` set to `contact` and each with a unique `value` that uniquely identifies that individual radio button within the group. They each also have a unique {{domxref("Element.id", "id")}}, which is used by the {{HTMLElement("label")}} element's [`for`](/en-US/docs/Web/HTML/Element/label#for) attribute to associate the labels with the radio buttons. You can try out this example here: {{EmbedLiveSample('Defining_a_radio_group', 600, 130)}} ### Data representation of a radio group When the above form is submitted with a radio button selected, the form's data includes an entry in the form `contact=value`. For example, if the user clicks on the "Phone" radio button then submits the form, the form's data will include the line `contact=phone`. If you omit the `value` attribute in the HTML, the submitted form data assigns the value `on` to the group. In this scenario, if the user clicked on the "Phone" option and submitted the form, the resulting form data would be `contact=on`, which isn't helpful. So don't forget to set your `value` attributes! > **Note:** If no radio button is selected when the form is submitted, the radio group is not included in the submitted form data at all, since there is no value to report. It's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the `checked` state. See [Selecting a radio button by default](#selecting_a_radio_button_by_default) below. Let's add a bit of code to our example so we can examine the data generated by this form. The HTML is revised to add a {{HTMLElement("pre")}} block to output the form data into: ```html <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> <pre id="log"></pre> ``` Then we add some [JavaScript](/en-US/docs/Web/JavaScript) to set up an event listener on the {{domxref("HTMLFormElement/submit_event", "submit")}} event, which is sent when the user clicks the "Submit" button: ```js const form = document.querySelector("form"); const log = document.querySelector("#log"); form.addEventListener( "submit", (event) => { const data = new FormData(form); let output = ""; for (const entry of data) { output = `${output}${entry[0]}=${entry[1]}\r`; } log.innerText = output; event.preventDefault(); }, false, ); ``` Try this example out and see how there's never more than one result for the `contact` group. {{EmbedLiveSample("Data_representation_of_a_radio_group", 600, 130)}} ## Additional attributes In addition to the common attributes shared by all {{HTMLElement("input")}} elements, `radio` inputs support the following attributes. - `checked` - : A Boolean attribute which, if present, indicates that this radio button is the default selected one in the group. Unlike other browsers, Firefox by default [persists the dynamic checked state](https://stackoverflow.com/questions/5985839/bug-with-firefox-disabled-attribute-of-input-not-resetting-when-refreshing) of an `<input>` across page loads. Use the [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) attribute to control this feature. - `value` - : The `value` attribute is one which all {{HTMLElement("input")}}s share; however, it serves a special purpose for inputs of type `radio`: when a form is submitted, only radio buttons which are currently checked are submitted to the server, and the reported value is the value of the `value` attribute. If the `value` is not otherwise specified, it is the string `on` by default. This is demonstrated in the section [Value](#value) above. - `required` - : The `required` attribute is one which most {{HTMLElement("input")}}s share. If any radio button in a same-named group of radio buttons has the `required` attribute, a radio button in that group must be checked, although it doesn't have to be the one with the attribute applied. ## Using radio inputs We already covered the fundamentals of radio buttons above. Let's now look at the other common radio-button-related features and techniques you may need to know about. ### Selecting a radio button by default To make a radio button selected by default, you include `checked` attribute, as shown in this revised version of the previous example: ```html <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" checked /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> ``` {{EmbedLiveSample('Selecting_a_radio_button_by_default', 600, 130)}} In this case, the first radio button is now selected by default. > **Note:** If you put the `checked` attribute on more than one radio button, later instances will override earlier ones; that is, the last `checked` radio button will be the one that is selected. This is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a new one is marked as checked. ### Providing a bigger hit area for your radio buttons In the above examples, you may have noticed that you can select a radio button by clicking on its associated {{htmlelement("label")}} element, as well as on the radio button itself. This is a really useful feature of HTML form labels that makes it easier for users to click the option they want, especially on small-screen devices like smartphones. Beyond accessibility, this is another good reason to properly set up `<label>` elements on your forms. ## Validation Radio buttons don't participate in constraint validation; they have no real value to be constrained. ## Styling radio inputs The following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this: ```html <form> <fieldset> <legend>Please select your preferred contact method:</legend> <div> <input type="radio" id="contactChoice1" name="contact" value="email" checked /> <label for="contactChoice1">Email</label> <input type="radio" id="contactChoice2" name="contact" value="phone" /> <label for="contactChoice2">Phone</label> <input type="radio" id="contactChoice3" name="contact" value="mail" /> <label for="contactChoice3">Mail</label> </div> <div> <button type="submit">Submit</button> </div> </fieldset> </form> ``` The CSS involved in this example is a bit more significant: ```css html { font-family: sans-serif; } div:first-of-type { display: flex; align-items: flex-start; margin-bottom: 5px; } label { margin-right: 15px; line-height: 32px; } input { appearance: none; border-radius: 50%; width: 16px; height: 16px; border: 2px solid #999; transition: 0.2s all linear; margin-right: 5px; position: relative; top: 4px; } input:checked { border: 6px solid black; } button, legend { color: white; background-color: black; padding: 5px 10px; border-radius: 0; border: 0; font-size: 14px; } button:hover, button:focus { color: #999; } button:active { background-color: white; color: black; outline: 1px solid black; } ``` Most notable here is the use of the {{cssxref("appearance")}} property (with prefixes needed to support some browsers). By default, radio buttons (and [checkboxes](/en-US/docs/Web/HTML/Element/input/checkbox)) are styled with the operating system's native styles for those controls. By specifying `appearance: none`, you can remove the native styling altogether, and create your own styles for them. Here we've used a {{cssxref("border")}} along with {{cssxref("border-radius")}} and a {{cssxref("transition")}} to create a nice animating radio selection. Notice also how the {{cssxref(":checked")}} pseudo-class is used to specify the styles for the radio button's appearance when selected. > **Note:** If you wish to use the {{cssxref("appearance")}} property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword `none` does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers. {{EmbedLiveSample('Styling_radio_inputs', 600, 120)}} Notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you'd want in a real web application, but it definitely shows off the possibilities. ## Technical summary <table class="properties"> <tbody> <tr> <td><strong><a href="#value">Value</a></strong></td> <td> A string representing the value of the radio button. </td> </tr> <tr> <td><strong>Events</strong></td> <td>{{domxref("HTMLElement/change_event", "change")}} and {{domxref("Element/input_event", "input")}}</td> </tr> <tr> <td><strong>Supported common attributes</strong></td> <td> <code><a href="#checked">checked</a></code >, <code><a href="#value">value</a></code> and <code ><a href="/en-US/docs/Web/HTML/Attributes/required">required</a></code > </td> </tr> <tr> <td><strong>IDL attributes</strong></td> <td><code>checked</code> and <code>value</code></td> </tr> <tr> <td><strong>DOM interface</strong></td> <td><p>{{domxref("HTMLInputElement")}}</p></td> </tr> <tr> <td><strong>Methods</strong></td> <td> {{domxref("HTMLInputElement.select", "select()")}} </td> </tr> <tr> <td><strong>Implicit ARIA Role</strong></td> <td> <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role">radio</a></code> </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("input")}} and the {{domxref("HTMLInputElement")}} interface that implements it. - {{domxref("RadioNodeList")}}: the interface that describes a list of radio buttons - [Compatibility of CSS properties](/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_controls)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/details/index.md
--- title: "<details>: The Details disclosure element" slug: Web/HTML/Element/details page-type: html-element browser-compat: html.elements.details --- {{HTMLSidebar}} The **`<details>`** [HTML](/en-US/docs/Web/HTML) element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the {{HTMLElement("summary")}} element. A disclosure widget is typically presented onscreen using a small triangle that rotates (or twists) to indicate open/closed status, with a label next to the triangle. The contents of the `<summary>` element are used as the label for the disclosure widget. The contents of the `<details>` provide the {{glossary("accessible description")}} for the `<summary>`. {{EmbedInteractiveExample("pages/tabbed/details.html", "tabbed-shorter")}} A `<details>` widget can be in one of two states. The default _closed_ state displays only the triangle and the label inside `<summary>` (or a {{Glossary("user agent")}}-defined default string if no `<summary>`). When the user clicks on the widget or focuses it then presses the space bar, it "twists" open, revealing its contents. The common use of a triangle which rotates or twists around to represent opening or closing the widget is why these are sometimes called "twisty". You can use CSS to style the disclosure widget, and you can programmatically open and close the widget by setting/removing its [`open`](#open) attribute. Unfortunately, at this time, there's no built-in way to animate the transition between open and closed. By default when closed, the widget is only tall enough to display the disclosure triangle and summary. When open, it expands to display the details contained within. Fully standards-compliant implementations automatically apply the CSS `{{cssxref("display")}}: list-item` to the {{HTMLElement("summary")}} element. You can use this to customize its appearance further. See [Customizing the disclosure widget](#customizing_the_disclosure_widget) for further details. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `open` - : This Boolean attribute indicates whether the details — that is, the contents of the `<details>` element — are currently visible. The details are shown when this attribute exists, or hidden when this attribute is absent. By default this attribute is absent which means the details are not visible. > **Note:** You have to remove this attribute entirely to make the details hidden. `open="false"` makes the details visible because this attribute is Boolean. ## Events In addition to the usual events supported by HTML elements, the `<details>` element supports the {{domxref("HTMLDetailsElement/toggle_event", "toggle")}} event, which is dispatched to the `<details>` element whenever its state changes between open and closed. It is sent _after_ the state is changed, although if the state changes multiple times before the browser can dispatch the event, the events are coalesced so that only one is sent. You can use an event listener for the `toggle` event to detect when the widget changes state: ```js details.addEventListener("toggle", (event) => { if (details.open) { /* the element was toggled open */ } else { /* the element was toggled closed */ } }); ``` ## Examples ### A simple disclosure example This example shows a simple `<details>` element with a `<summary>`. ```html <details> <summary>System Requirements</summary> <p> Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended. </p> </details> ``` #### Result {{EmbedLiveSample("A_simple_disclosure_example", 650, 150)}} ### Creating an open disclosure box To start the `<details>` box in its open state, add the Boolean `open` attribute: ```html <details open> <summary>System Requirements</summary> <p> Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended. </p> </details> ``` #### Result {{EmbedLiveSample("Creating_an_open_disclosure_box", 650, 150)}} ### Customizing the appearance Now let's apply some CSS to customize the appearance of the disclosure box. #### CSS ```css details { font: 16px "Open Sans", Calibri, sans-serif; width: 620px; } details > summary { padding: 2px 6px; width: 15em; background-color: #ddd; border: none; box-shadow: 3px 3px 4px black; cursor: pointer; } details > p { border-radius: 0 0 10px 10px; background-color: #ddd; padding: 2px 6px; margin: 0; box-shadow: 3px 3px 4px black; } details[open] > summary { background-color: #ccf; } ``` This CSS creates a look similar to a tabbed interface, where clicking the tab opens it to reveal its contents. The selector `details[open]` can be used to style the element which is open. #### HTML ```html <details> <summary>System Requirements</summary> <p> Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended. </p> </details> ``` #### Result {{EmbedLiveSample("Customizing_the_appearance", 650, 150)}} ### Customizing the disclosure widget The disclosure triangle itself can be customized, although this is not as broadly supported. There are variations in how browsers support this customization due to experimental implementations as the element was standardized, so we'll have to use multiple approaches for a while. The {{HTMLElement("summary")}} element supports the {{cssxref("list-style")}} shorthand property and its longhand properties, such as {{cssxref("list-style-type")}}, to change the disclosure triangle to whatever you choose (usually with {{cssxref("list-style-image")}}). For example, we can remove the disclosure widget icon by setting `list-style: none`. #### CSS ```css details { font: 16px "Open Sans", Calibri, sans-serif; width: 620px; } details > summary { padding: 2px 6px; width: 15em; background-color: #ddd; border: none; box-shadow: 3px 3px 4px black; cursor: pointer; list-style: none; } details > p { border-radius: 0 0 10px 10px; background-color: #ddd; padding: 2px 6px; margin: 0; box-shadow: 3px 3px 4px black; } ``` This CSS creates a look similar to a tabbed interface, where activating the tab expands and opens it to reveal its contents. #### HTML ```html <details> <summary>System Requirements</summary> <p> Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended. </p> </details> ``` #### Result {{EmbedLiveSample("Customizing_the_disclosure_widget", 650, 150)}} ## 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 >, sectioning root, interactive content, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> One {{HTMLElement("summary")}} element followed by <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow 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#flow_content" >flow content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></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("HTMLDetailsElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("summary")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/rt/index.md
--- title: "<rt>: The Ruby Text element" slug: Web/HTML/Element/rt page-type: html-element browser-compat: html.elements.rt --- {{HTMLSidebar}} The **`<rt>`** [HTML](/en-US/docs/Web/HTML) element specifies the ruby text component of a ruby annotation, which is used to provide pronunciation, translation, or transliteration information for East Asian typography. The `<rt>` element must always be contained within a {{HTMLElement("ruby")}} element. {{EmbedInteractiveExample("pages/tabbed/rt.html", "tabbed-shorter")}} See the article about the {{HTMLElement("ruby")}} element for more examples. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ### Using ruby annotations This simple example provides Romaji transliteration for the kanji characters within the {{HTMLElement("ruby")}} element: ```html <ruby> 漢 <rt>Kan</rt> 字 <rt>ji</rt> </ruby> ``` ```css hidden body { font-size: 22px; } ``` #### Result {{EmbedLiveSample("Using_ruby_annotations", 600, 60)}} ## 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#phrasing_content" >Phrasing content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The end tag may be omitted if the <code>&#x3C;rt></code> element is immediately followed by an <code>&#x3C;rt></code> or {{HTMLElement("rp")}} 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">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("ruby")}} - {{HTMLElement("rp")}} - {{HTMLElement("rb")}} - {{HTMLElement("rtc")}} - {{CSSXRef("text-transform", "text-transform: full-size-kana")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/progress/index.md
--- title: "<progress>: The Progress Indicator element" slug: Web/HTML/Element/progress page-type: html-element browser-compat: html.elements.progress --- {{HTMLSidebar}} The **`<progress>`** [HTML](/en-US/docs/Web/HTML) element displays an indicator showing the completion progress of a task, typically displayed as a progress bar. {{EmbedInteractiveExample("pages/tabbed/progress.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `max` - : This attribute describes how much work the task indicated by the `progress` element requires. The `max` attribute, if present, must have a value greater than `0` and be a valid floating point number. The default value is `1`. - `value` - : This attribute specifies how much of the task that has been completed. It must be a valid floating point number between `0` and `max`, or between `0` and `1` if `max` is omitted. If there is no `value` attribute, the progress bar is indeterminate; this indicates that an activity is ongoing with no indication of how long it is expected to take. > **Note:** Unlike the {{htmlelement("meter")}} element, the minimum value is always 0, and the `min` attribute is not allowed for the `<progress>` element. > **Note:** The {{cssxref(":indeterminate")}} pseudo-class can be used to match against indeterminate progress bars. To change the progress bar to indeterminate after giving it a value you must remove the value attribute with {{domxref("Element.removeAttribute", "element.removeAttribute('value')")}}. ## Examples ```html <progress value="70" max="100">70 %</progress> ``` ### Result {{ EmbedLiveSample("Examples", 200, 50) }} ## Accessibility concerns ### Labelling In most cases you should provide an accessible label when using `<progress>`. While you can use the standard ARIA labelling attributes [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) or [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) as you would for any element with `role="progressbar"`, when using `<progress>` you can alternatively use the {{htmlelement("label")}} element. > **Note:** Text placed between the element's tags is not an accessible label, it is only recommended as a fallback for old browsers that do not support this element. #### Examples ```html <label> Uploading Document: <progress value="70" max="100">70 %</progress> </label> <!-- OR --> <br /> <label for="progress-bar">Uploading Document</label> <progress id="progress-bar" value="70" max="100">70 %</progress> ``` #### Result {{EmbedLiveSample('Labelling')}} ### Describing a particular region If the `<progress>` element is describing the loading progress of a section of a page, use [`aria-describedby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-describedby) to point to the status, and set [`aria-busy="true"`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy) on the section that is being updated, removing the `aria-busy` attribute when it has finished loading. #### Examples ```html <div aria-busy="true" aria-describedby="progress-bar"> <!-- content is for this region is loading --> </div> <!-- ... --> <progress id="progress-bar" aria-label="Content loading…"></progress> ``` ##### Result {{EmbedLiveSample('Describing a particular region')}} ## 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>, labelable content, <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content">palpable 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>, but there must be no <code>&#x3C;progress></code> element among its descendants. </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="/en-US/docs/Web/Accessibility/ARIA/Roles/progressbar_role"><code>progressbar</code></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("HTMLProgressElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{htmlelement("meter")}} - {{ cssxref(":indeterminate") }} - {{ cssxref("-moz-orient") }} - {{ cssxref("::-moz-progress-bar") }} - {{ cssxref("::-webkit-progress-bar") }} - {{ cssxref("::-webkit-progress-value") }} - {{ cssxref("::-webkit-progress-inner-element") }}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/th/index.md
--- title: "<th>: The Table Header element" slug: Web/HTML/Element/th page-type: html-element browser-compat: html.elements.th --- {{HTMLSidebar}} The **`<th>`** [HTML](/en-US/docs/Web/HTML) element defines a cell as the header of a group of table cells and may be used as a child of the {{HTMLElement("tr")}} element. The exact nature of this group is defined by the [`scope`](#scope) and [`headers`](#headers) attributes. {{EmbedInteractiveExample("pages/tabbed/th.html","tabbed-taller")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `abbr` - : A short, abbreviated description of the header cell's content provided as an alternative label to use for the header cell when referencing the cell in other contexts. Some user-agents, such as speech readers, may present this description before the content itself. - `colspan` - : A non-negative integer value indicating how many columns the header cell spans or extends. The default value is `1`. User agents dismiss values higher than 1000 as incorrect, defaulting such values to `1`. - `headers` - : A list of space-separated strings corresponding to the `id` attributes of the `<th>` elements that provide the headers for this header cell. - `rowspan` - : A non-negative integer value indicating how many rows the header cell spans or extends. The default value is `1`; if its value is set to `0`, the header cell will extends to the end of the table grouping section ({{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, even if implicitly defined), that the `<th>` belongs to. Values higher than `65534` are clipped at `65534`. - `scope` - : Defines the cells that the header (defined in the `<th>`) element relates to. Possible {{Glossary("enumerated", "enumerated")}} values are: - `row`: the header relates to all cells of the row it belongs to; - `col`: the header relates to all cells of the column it belongs to; - `rowgroup`: the header belongs to a rowgroup and relates to all of its cells; - `colgroup`: the header belongs to a colgroup and relates to all of its cells. If the `scope` attribute is not specified, or its value is not `row`, `col`, `rowgroup`, or `colgroup`, then browsers automatically select the set of cells to which the header cell applies. ### 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 the header 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 header cell applies to. Use the [`scope`](#scope) attribute instead, as this attribute is deprecated. - `bgcolor` {{deprecated_inline}} - : Defines the background color of the header 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 header 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 header cell content from the alignment character specified by the [`char`](#char) attribute. - `height` {{deprecated_inline}} - : Defines a recommended header cell height. Use the {{cssxref("height")}} CSS property instead, as this attribute is deprecated. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of the header 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 header cell width. Use the {{cssxref("width")}} CSS property instead, as this attribute is deprecated. ## Usage notes - The `<th>` may only be used within a {{HTMLElement("tr")}} element. - In simple contexts, using the [`scope`](#scope) attribute on header cells (`<th>` elements) is redundant because [`scope`](#scope) is inferred. However, certain assistive technologies may fail to infer correctly, so specifying header scope may improve user experiences. - When using the [`colspan`](#colspan) and [`rowspan`](#rowspan) attributes to span header 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 column and row headers This example uses `<th>` elements to introduce column and row headers in a basic table structure. #### HTML The first row ({{HTMLElement("tr")}} element) contains the column headers (`<th>` elements), which act as "titles" for the columns to make it easier to understand the information in the columns and identify the data. To indicate that each column header relates to all cells in the corresponding column, the [`scope`](#scope) attribute is set to `col` (column). The remaining rows contain the main data of the table. Each of these rows has a row header (`<th>` element) introduced as the first cell. This creates a column with row headers as the first column of the table. Similar to the column headers, the [`scope`](#scope) attribute is set to `row` to specify which cells each row header relates to, which in the example below are all data cells ({{HTMLElement("td")}} elements) in each `row`. > **Note:** Normally, the grouping elements {{HTMLElement("thead")}} and {{HTMLElement("tbody")}} are used to group rows with headers into the respective table head and body sections. These elements are omitted in this example to reduce complexity and enable focusing on the use of header cells. ```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 Some basic CSS is used to style the table and its cells. We use CSS [attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors) to target header cells based on their [`scope`](#scope) attribute values, highlighting column and row headers (`<th>` elements) and differentiating them each other and from the data cells ({{HTMLElement("td")}}). ```css th, td { border: 1px solid rgb(160 160 160); padding: 8px 10px; } th[scope="col"] { background-color: #505050; color: #fff; } th[scope="row"] { background-color: #d6ecd4; } tr:nth-of-type(odd) td { background-color: #eee; } ``` ```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_column_and_row_headers", 650, 170)}} ### Column and row spanning This example extends and enhances the basic table from the [previous example](#basic_column_and_row_headers) by adding a second row for additional column headers. #### HTML An additional table row ({{HTMLElement("tr")}} element) is added as the second header row of the table with two additional column headers (`<th>` elements). In this way, the "Pronunciation" column is split into two columns, one for the IPA (International Phonetic Alphabet) notation and one for the respelling (the original pronunciation column). The corresponding data cells ({{HTMLElement("td")}} elements) are added to each subsequent row. As shown in the [usage notes](#usage_notes), the [`colspan`](#colspan) and [`rowspan`](#rowspan) attributes can be used for the `<th>` elements to allocate the header cells to the correct columns and rows. To achieve a "two-row" header in the table structure, the first two header cells within the first {{HTMLElement("tr")}} element are spanned across two rows. The third header cell is spanned two columns wide (remaining in the first row). This setup leaves two available areas in the third and fourth columns in the second row, where the two headers within the second {{HTMLElement("tr")}} element are automatically placed, with the default value being `1` for the [`colspan`](#colspan) and [`rowspan`](#rowspan) attributes. > **Note:** Normally, {{HTMLElement("thead")}} and {{HTMLElement("tbody")}} elements are used to group rows with headers into the respective table head and body sections. This is not implemented in this example to focus on the headers and spanning and reduce the example's complexity. ```html <table> <tr> <th scope="col" rowspan="2">Symbol</th> <th scope="col" rowspan="2">Code word</th> <th scope="col" colspan="2">Pronunciation</th> </tr> <tr> <th scope="col">IPA</th> <th scope="col">Respelling</th> </tr> <tr> <th scope="row">A</th> <td>Alfa</td> <td>ˈælfa</td> <td>AL fah</td> </tr> <tr> <th scope="row">B</th> <td>Bravo</td> <td>ˈbraːˈvo</td> <td>BRAH voh</td> </tr> <tr> <th scope="row">C</th> <td>Charlie</td> <td>ˈtʃɑːli</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td>ˈdeltɑ</td> <td>DELL tah</td> </tr> </table> ``` #### CSS The CSS is unchanged from the [previous example](#basic_column_and_row_headers). ```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; } th[scope="col"] { background-color: #505050; color: #fff; } th[scope="row"] { background-color: #d6ecd4; } tr:nth-of-type(odd) td { background-color: #eee; } ``` #### Result {{EmbedLiveSample("Column_and_row_spanning", 650, 200)}} ### Associate header cells with other header cells For more complex relationships between header cells, using `th` elements with the [`scope`](#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 header cell, the [`headers`](#headers) attribute can be introduced along with [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attributes. Because of the way the "Pronunciation" column is split into two columns in the example, introducing a "two row" header, assistive technologies such as screen readers may not be able to identify which additional header cells (`th` elements) the "Pronunciation" header cell is related to and vice versa. Therefore, the [`headers`](#headers) attribute is used on the "Pronunciation", "IPA", and "Respelling" header cells to associate the related header cells based on the values of the unique identifiers from the added [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attributes in the form of a space-separated list. > **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 scope="col" rowspan="2">Symbol</th> <th scope="col" rowspan="2">Code word</th> <th scope="col" colspan="2" id="p" headers="i r">Pronunciation</th> </tr> <tr> <th scope="col" id="i" headers="p">IPA</th> <th scope="col" id="r" headers="p">Respelling</th> </tr> <tr> <th scope="row">A</th> <td>Alfa</td> <td>ˈælfa</td> <td>AL fah</td> </tr> <tr> <th scope="row">B</th> <td>Bravo</td> <td>ˈbraːˈvo</td> <td>BRAH voh</td> </tr> <tr> <th scope="row">C</th> <td>Charlie</td> <td>ˈtʃɑːli</td> <td>CHAR lee</td> </tr> <tr> <th scope="row">D</th> <td>Delta</td> <td>ˈdeltɑ</td> <td>DELL tah</td> </tr> </table> ``` #### Result The [visual result](#result_2) is unchanged from the [previous example table](#column_and_row_spanning). ## 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 header, footer, sectioning content, or heading content descendants. </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> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/columnheader_role"><code>columnheader</code></a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/rowheader_role"><code>rowheader</code></a> </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("td")}}, {{HTMLElement("tfoot")}}, {{HTMLElement("thead")}}, {{HTMLElement("tr")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each header cell - {{cssxref("border")}}: CSS property to control borders of header cells - {{cssxref("height")}}: CSS property to control the recommended header cell height - {{cssxref("text-align")}}: CSS property to horizontally align each header cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each header cell content - {{cssxref("width")}}: CSS property to control the recommended header cell width - {{cssxref(":nth-of-type")}}, {{cssxref(":first-of-type")}}, {{cssxref(":last-of-type")}}: CSS pseudo-classes to select the desired header cells
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/th/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/pre/index.md
--- title: "<pre>: The Preformatted Text element" slug: Web/HTML/Element/pre page-type: html-element browser-compat: html.elements.pre --- {{HTMLSidebar}} The **`<pre>`** [HTML](/en-US/docs/Web/HTML) element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional, or [monospaced](https://en.wikipedia.org/wiki/Monospaced_font), font. Whitespace inside this element is displayed as written. By default, `<pre>` is a [block-level](/en-US/docs/Glossary/Block-level_content) element, i.e. its default {{cssxref("display")}} value is `block`. {{EmbedInteractiveExample("pages/tabbed/pre.html", "tabbed-standard")}} If you have to display reserved characters such as `<`, `>`, `&`, and `"` within the `<pre>` tag, the characters must be escaped using their respective [HTML entity](/en-US/docs/Glossary/Entity). ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `cols` {{non-standard_inline}} {{deprecated_inline}} - : Contains the _preferred_ count of characters that a line should have. It was a non-standard synonym of [`width`](#width). To achieve such an effect, use CSS {{Cssxref("width")}} instead. - `width` {{deprecated_inline}} {{Non-standard_Inline}} - : Contains the _preferred_ count of characters that a line should have. Though technically still implemented, this attribute has no visual effect; to achieve such an effect, use CSS {{Cssxref("width")}} instead. - `wrap` {{non-standard_inline}} {{Deprecated_Inline}} - : Is a _hint_ indicating how the overflow must happen. In modern browser this hint is ignored and no visual effect results in its present; to achieve such an effect, use CSS {{Cssxref("white-space")}} instead. ## Accessibility concerns It is important to provide an alternate description for any images or diagrams created using preformatted text. The alternate description should clearly and concisely describe the image or diagram's content. People experiencing low vision conditions and browsing with the aid of assistive technology such as a screen reader may not understand what the preformatted text characters are representing when they are read out in sequence. A combination of the {{HTMLElement("figure")}} and {{HTMLElement("figcaption")}} elements, supplemented by the [ARIA](/en-US/docs/Web/Accessibility/ARIA) `role` and [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attributes on the `pre` element allow the preformatted {{Glossary("ASCII")}} art to be announced as an image with alternative text, and the `figcaption` serving as the image's caption. ### Example ```html <figure> <pre role="img" aria-label="ASCII COW"> ___________________________ &lt; I'm an expert in my field. &gt; --------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || </pre> <figcaption id="cow-caption"> A cow saying, "I'm an expert in my field." The cow is illustrated using preformatted text characters. </figcaption> </figure> ``` - [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) - [H86: Providing text alternatives for ASCII art, emoticons, and leetspeak | W3C Techniques for WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/H86.html) ## Examples ### Basic example #### HTML ```html <p>Using CSS to change the font color is easy.</p> <pre> body { color: red; } </pre> ``` #### Result {{EmbedLiveSample("Basic_example")}} ### Escaping reserved characters #### HTML ```html <pre> let i = 5; if (i &lt; 10 &amp;&amp; i &gt; 0) return &quot;Single Digit Number&quot; </pre> ``` #### Result {{EmbedLiveSample("Escaping_reserved_characters")}} ## 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 >, 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#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("HTMLPreElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - CSS: {{Cssxref('white-space')}}, {{Cssxref('word-break')}} - [HTML Entity](/en-US/docs/Glossary/Entity) - Related element: {{HTMLElement("code")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/table/index.md
--- title: "<table>: The Table element" slug: Web/HTML/Element/table page-type: html-element browser-compat: html.elements.table --- {{HTMLSidebar}} The **`<table>`** [HTML](/en-US/docs/Web/HTML) element represents tabular data—that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. {{EmbedInteractiveExample("pages/tabbed/table.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 the table within its parent element. The possible {{Glossary("enumerated")}} values are `left`, `center`, and `right`. Use the {{cssxref("margin-inline-start")}} and {{cssxref("margin-inline-end")}} CSS properties instead, as this attribute is deprecated. - `bgcolor` {{deprecated_inline}} - : Defines the background color of the table. 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. - `border` {{deprecated_inline}} - : Defines, as a non-negative integer value (in pixels), the size of the frame surrounding the table. If set to `0`, the [`frame`](#frame) attribute is set to void. Use the {{cssxref("border")}} CSS property instead, as this attribute is deprecated. - `cellpadding` {{deprecated_inline}} - : Defines the space between the content of a cell and its border, displayed or not. If the cellpadding's length is defined in pixels, this pixel-sized space will be applied to all four sides of the cell's content. If the length is defined using a percentage value, the content will be centered and the total vertical space (top and bottom) will represent this value. The same is true for the total horizontal space (left and right). Apply the {{cssxref("border-collapse")}} CSS property to the `<table>` element, with its value set to `collapse`, and the {{cssxref("padding")}} CSS property to the {{HTMLElement("td")}} elements instead, as this attribute is deprecated. - `cellspacing` {{deprecated_inline}} - : Defines the size of the space between two cells in a percentage value or pixels. The attribute is applied both horizontally and vertically, to the space between the top of the table and the cells of the first row, the left of the table and the first column, the right of the table and the last column and the bottom of the table and the last row. Apply the {{cssxref("border-spacing")}} CSS property to the `<table>` element instead, as this attribute is deprecated. `border-spacing` does not have any effect if the {{cssxref("border-collapse")}} CSS property is set to `collapse`. - `frame` {{deprecated_inline}} - : Defines which side of the frame surrounding the table must be displayed. The possible {{Glossary("enumerated")}} values are `void`, `above`, `below`, `hsides`, `vsides`, `lhs`, `rhs`, `box` and `border`. Use the {{cssxref("border-style")}} and {{cssxref("border-width")}} CSS properties instead, as this attribute is deprecated. - `rules` {{deprecated_inline}} - : Defines where rules (borders) are displayed in the table. The possible {{Glossary("enumerated")}} values are `none` (default value), `groups` ({{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, and {{HTMLElement("tfoot")}} elements), `rows` (horizontal lines), `cols` (vertical lines), and `all` (border around every cell). Use the {{cssxref("border")}} CSS property on the appropriate table-related elements, as well as on the `<table>` itself, instead, as this attribute is deprecated. - `summary` {{deprecated_inline}} - : Defines an alternative text that summarizes the content of the table. Use the {{htmlelement("caption")}} element instead, as this attribute is deprecated. - `width` {{deprecated_inline}} - : Specifies the width of the table. Use the {{cssxref("width")}} CSS property instead, as this attribute is deprecated. > **Note:** While no HTML specification includes `height` as a `<table>` attribute, some browsers support a non-standard interpretation of `height`. The unitless value sets a minimum absolute height in pixels. If set as a percent value, the minimum table height will be relative to the parent container's height. Use the {{cssxref("min-height")}} CSS property instead, as this attribute is deprecated. ## Visual layout of table contents Following elements are part of the table structure: - {{HTMLElement("caption")}} - {{HTMLElement("thead")}} - {{HTMLElement("colgroup")}} - {{HTMLElement("col")}} - {{HTMLElement("th")}} - {{HTMLElement("tbody")}} - {{HTMLElement("tr")}} - {{HTMLElement("td")}} - {{HTMLElement("tfoot")}} The `<table>` box establishes a table formatting context. Elements inside the `<table>` generate rectangular boxes. Each box occupies a number of table cells according to the following rules: 1. The row boxes fill the table in the source code order from top to bottom. Each row box occupies one row of cells. 2. A row group box occupies one or more row boxes. 3. Column boxes are placed next to each other in source code order. Depending on the value of the [`dir`](/en-US/docs/Web/HTML/Global_attributes/dir) attribute, the columns are laid in left-to-right or right-to-left direction. A column box occupies one or more columns of table cells. 4. A column group box occupies one or more column boxes. 5. A cell box may span over multiple rows and columns. User agents trim cells to fit in the available number of rows and columns. Table cells do have padding. Boxes that make up a table do not have margins. ### Table layers and transparency For styling purpose the table elements may be thought of as being put on six superimposed layers: ![Table element layers](table_element_layers.png) The background set on an element in one layer will be visible only if the layers above it have transparent background. A missing cell is rendered as if an anonymous table-cell box occupied that place. ## Examples The examples below include tables of progressively increasing complexity. For additional examples, including an in-depth tutorial, see the [HTML tables](/en-US/docs/Learn/HTML/Tables) series in the [Learn web development](/en-US/docs/Learn) area, where you'll learn how to use the table elements and their attributes to correctly structure your tabular data. A [Styling tables](/en-US/docs/Learn/CSS/Building_blocks/Styling_tables) guide provides table styling information, including common, useful techniques. Since the structure of a `<table>` involves the use of several table-related HTML elements along with various associated attributes, the following examples are intended to provide a simplified explanation that covers the basics and common standards. Additional and more detailed information can be found on the corresponding linked pages. These table examples demonstrate how to create an {{Glossary("accessibility", "accessible")}} table that is structured with HTML and styled with [CSS](/en-US/docs/Web/CSS). Because of how HTML tables are structured, the {{Glossary("markup", "markup")}} can quickly grow. For this reason, it is important to clearly define the table's purpose and final appearance to create the appropriate structure. A logical structure developed with {{Glossary("semantics", "semantic")}} markup is not only easier to style, but enables useful and accessible tables that can be understood and navigated by everyone, including search engines and users of assistive technologies. The first example is basic, with subsequent examples growing in complexity. First, we will develop a very basic HTML table structure for the table. The first two examples contain no table section groups such as a defined head, body, or foot, and involve no cell spanning or explicitly defined cell relationships. Not even a caption is provided. As we work through the examples, they will be progressively enhanced to include all the table features that a complex data table should possess. ### Basic table This example includes a _very_ basic table with three rows and two columns. To demonstrate default browser table styles, no CSS has been included in this example. #### HTML The table rows are defined with {{HTMLElement("tr")}} elements, and the columns are defined with table header and data cells within them. The first row contains the header cells ({{HTMLElement("th")}} elements) that serve as column headers for the data cells ({{HTMLElement("td")}} elements). Each element ({{HTMLElement("th")}} or {{HTMLElement("td")}}) per row is in its respective column—that is, the first element of a row is in the first column, and the second element of that row is in the second column. ```html <table> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>Maria Sanchez</td> <td>28</td> </tr> <tr> <td>Michael Johnson</td> <td>34</td> </tr> </table> ``` #### Result There is no custom [CSS](/en-US/docs/Web/CSS) or [user stylesheet](/en-US/docs/Web/CSS/Cascade#author_stylesheets) applied to this table. The styling results purely from the [user-agent stylesheet](/en-US/docs/Web/CSS/Cascade#user-agent_stylesheets). {{EmbedLiveSample('Basic_table', 650, 80)}} ### Expanded table with header cells This example extends the [basic table](#basic_table), extending the content and adding basic CSS styles. #### HTML The table comprises four rows ({{HTMLElement("tr")}} elements) now, with four columns each. The first row is a row of header cells (The first row contains only {{HTMLElement("th")}} elements). Subsequent rows include a header column ({{HTMLElement("th")}} elements as the first child elements of each row) and three data columns ({{HTMLElement("td")}} elements). As table sectioning elements are not used, the browser automatically defines the content group structure, i.e., all rows are wrapped within the body of the table of an implicit {{HTMLElement("tbody")}} element. ```html <table> <tr> <th>Name</th> <th>ID</th> <th>Member Since</th> <th>Balance</th> </tr> <tr> <th>Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>0.00</td> </tr> <tr> <th>Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td>37.00</td> </tr> <tr> <th>Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>15.00</td> </tr> </table> ``` #### CSS With CSS, we provide the basic styling to create lines around the components of the table to make the data structure clearer. The CSS adds a solid border around the `<table>` and around each of the table's cells, including those specified with both {{HTMLElement("th")}} and {{HTMLElement("td")}} elements, demarcating every header and data cells. ```css table { border: 2px solid rgb(140 140 140); } th, td { border: 1px solid rgb(160 160 160); } ``` #### Result {{EmbedLiveSample("Expanded_table_with_header_cells", 650, 110)}} ### Specifying table cell relations Before moving on to extend the table in more advanced ways, it's advisable to improve {{Glossary("accessibility", "accessibility")}} by defining relationships between the header and data cells ({{HTMLElement("th")}} and {{HTMLElement("td")}} elements). #### HTML This is accomplished by introducing the [`scope`](/en-US/docs/Web/HTML/Element/th#scope) attribute on the {{HTMLElement("th")}} elements and setting the values to the corresponding `col` (column) or `row` value. ```html <table> <tr> <th scope="col">Name</th> <th scope="col">ID</th> <th scope="col">Member Since</th> <th scope="col">Balance</th> </tr> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>15.00</td> </tr> </table> ``` The CSS and visual result are unchanged—the adaptation provides valuable contextual information for assistive technologies such as screen readers to help identify which cells the headers relate to. > **Note:** If the table structure is even more complex, the (additional) use of the [`headers`](/en-US/docs/Web/HTML/Element/th#headers) attribute on the {{HTMLElement("th")}} and {{HTMLElement("td")}} elements may improve accessibility and help assistive technologies identify the relationships between cells; see [Complicated tables](#complicated_tables). ### Explicitly specifying table section groups In addition to improving accessibility by [specifying cell relations](#specifying_table_cell_relations), the {{Glossary("semantics", "semantics")}} of the table can be improved by introducing table section groups. #### HTML Since the first row ({{HTMLElement("tr")}} element) contains only column header cells and provides the header for the rest of the table's contents, it can be enclosed in the {{HTMLElement("thead")}} element to explicitly specify that row as the head section of the table. Moreover, what is automatically accomplished by the browser can also be defined explicitly—the body section of the table, which contains the main data of the table, is specified by enclosing the corresponding rows in the {{HTMLElement("tbody")}} element. The explicit use of the {{HTMLElement("tbody")}} element helps the browser to create the intended table structure, avoiding unwanted results. ```html <table> <thead> <tr> <th scope="col">Name</th> <th scope="col">ID</th> <th scope="col">Member Since</th> <th scope="col">Balance</th> </tr> </thead> <tbody> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>15.00</td> </tr> </tbody> </table> ``` Once again, the CSS and visual result are unchanged—specifying such table section groups provides valuable contextual information for assistive technologies, including screen readers and search engines, as well as for styling in the CSS, which will be shown ion a later example. ### Column and row spanning In this example, we extend the table even more by adding a column and introducing a multi-row head section. #### HTML Building on the table created so far, a new column for a "Membership End Date" is added in each body row with the {{HTMLElement("td")}} element. An additional row ({{HTMLElement("tr")}} element) is also added within the head section ({{HTMLElement("thead")}} element) to introduce a "Membership Dates" header as a heading for the "Joined" and "Canceled" columns. The creation of the second header row involves adding [`colspan`](/en-US/docs/Web/HTML/Element/th#colspan) and [`rowspan`](/en-US/docs/Web/HTML/Element/th#rowspan) attributes to the {{HTMLElement("th")}} elements to allocate the header cells to the correct columns and rows. ```html <table> <thead> <tr> <th scope="col" rowspan="2">Name</th> <th scope="col" rowspan="2">ID</th> <th scope="col" colspan="2">Membership Dates</th> <th scope="col" rowspan="2">Balance</th> </tr> <tr> <th scope="col">Joined</th> <th scope="col">Canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td><time datetime="2017-04-08">April 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </tbody> </table> ``` ```css hidden table { border: 2px solid rgb(140 140 140); } th, td { border: 1px solid rgb(160 160 160); } ``` #### Result {{EmbedLiveSample("Column_and_row_spanning", 650, 130)}} The head section now has two rows, one with the headers ({{HTMLElement("th")}} elements) "Name", "ID", "Membership Dates", and "Balance", and a "Membership Dates" header with two subheaders that are in a second row: "Joined" and "Canceled". This is accomplished by: - The first row's "Name", "ID", and "Balance" header cells span both table header rows by using the [`rowspan`](/en-US/docs/Web/HTML/Element/th#rowspan) attribute, making them each two rows tall. - The first row's "Membership Dates" header cell spans two columns using the [`colspan`](/en-US/docs/Web/HTML/Element/th#colspan) attribute, causing it to be two columns wide. - The second row contains only the two header cells "Joined" and "Canceled" because the other three columns are merged with the cells in the first row that span two rows. The two header cells are correctly positioned under the "Membership Dates" header. ### Table caption and column summary It's a common and advisable practice to provide a summary for the table's content, allowing users to quickly determine the table's relevance. Furthermore, the "Balance" column is summarized by displaying the sum of the balances of the individual members. #### HTML A table summary is added by using a table [caption](#captions) ({{HTMLElement("caption")}} element) as the first child element of the `<table>`. The caption provides the {{glossary("accessible description")}} for the table. Lastly, a table foot section ({{HTMLElement("tfoot")}} element) is added below the body, with a row that summarizes the "Balance" column by displaying a sum. The elements and attributes introduced earlier are applied. ```html <table> <caption> Status of the club members 2021 </caption> <thead> <tr> <th scope="col" rowspan="2">Name</th> <th scope="col" rowspan="2">ID</th> <th scope="col" colspan="2">Membership Dates</th> <th scope="col" rowspan="2">Balance</th> </tr> <tr> <th scope="col">Joined</th> <th scope="col">Canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td><time datetime="2017-04-08">April 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </tbody> <tfoot> <tr> <th scope="row" colspan="4">Total balance</th> <td>52.00</td> </tr> </tfoot> </table> ``` ```css hidden table { border: 2px solid rgb(140 140 140); } th, td { border: 1px solid rgb(160 160 160); } ``` #### Result {{EmbedLiveSample("Table_caption_and_column_summary", 650, 180)}} ### Basic table styling Let's apply a basic style to the table to adjust the typeface and add a {{cssxref("background-color")}} to the head and foot rows. The HTML is unchanged this time, so let's dive right into the CSS. ```html hidden <table> <caption> Status of the club members 2021 </caption> <thead> <tr> <th scope="col" rowspan="2">Name</th> <th scope="col" rowspan="2">ID</th> <th scope="col" colspan="2">Membership Dates</th> <th scope="col" rowspan="2">Balance</th> </tr> <tr> <th scope="col">Joined</th> <th scope="col">Canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td><time datetime="2017-04-08">April 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </tbody> <tfoot> <tr> <th scope="row" colspan="4">Total balance</th> <td>52.00</td> </tr> </tfoot> </table> ``` #### CSS While a {{cssxref("font")}} property is added to the `<table>` element here to set a more visually appealing typeface (or an abominable sans-serif typeface, depending on your personal opinion), the interesting part is the second style, where the {{HTMLElement("tr")}} elements located within the {{HTMLElement("thead")}} and {{HTMLElement("tfoot")}} are styled adding a light blue {{cssxref("background-color")}}. This is a way to quickly apply a background color to all the cells in specific sections simultaneously. ```css table { border: 2px solid rgb(140 140 140); font: 16px "Open Sans", Helvetica, Arial, sans-serif; } thead > tr, tfoot > tr { background-color: rgb(228 240 245); } th, td { border: 1px solid rgb(160 160 160); } ``` #### Result {{EmbedLiveSample("Basic_table_styling", 650, 180)}} ### Advanced table styling Now we'll go all-out, with styles on rows in the header and body areas both, including alternating row colors, cells with different colors depending on position within a row, and so forth. Let's take a look at the result first this time. #### Result Here's what the final table will look like: {{EmbedLiveSample("Advanced_table_styling", 650, 210)}} There is no change to the HTML again. See what proper preparation of the HTML structure can do? ```html hidden <table> <caption> Status of the club members 2021 </caption> <thead> <tr> <th scope="col" rowspan="2">Name</th> <th scope="col" rowspan="2">ID</th> <th scope="col" colspan="2">Membership Dates</th> <th scope="col" rowspan="2">Balance</th> </tr> <tr> <th scope="col">Joined</th> <th scope="col">Canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">Margaret Nguyen</th> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>n/a</td> <td>0.00</td> </tr> <tr> <th scope="row">Edvard Galinski</th> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time></td> <td><time datetime="2017-04-08">April 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">Hoshi Nakamura</th> <td>601942</td> <td><time datetime="2012-07-23">July 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </tbody> <tfoot> <tr> <th scope="row" colspan="4">Total balance</th> <td>52.00</td> </tr> </tfoot> </table> ``` #### CSS The CSS is much more involved this time. It's not complicated, but there's a lot going on. Let's break it down. Here the {{CSSxRef("border-collapse")}} and {{CSSxRef("border-spacing")}} properties are added to eliminate spacing between cells and collapse borders that touch one another to be a single border instead of winding up with double borders. Additionally, the {{HTMLElement("caption")}} is placed at the `bottom` of the table using the {{CSSxRef("caption-side")}} property: ```css table { border-collapse: collapse; border-spacing: 0; border: 2px solid rgb(140 140 140); font: 16px "Open Sans", Helvetica, Arial, sans-serif; } caption { caption-side: bottom; padding: 10px; font-weight: bold; } ``` Next, the {{CSSxRef("padding")}} property is used to give all the table cells space around their content. The {{CSSxRef("vertical-align")}} property aligns the content of the header cells to the `bottom` of the cell, which can be seen on the cells in the head that span two rows: ```css th, td { border: 1px solid rgb(160 160 160); padding: 4px 6px; } th { vertical-align: bottom; } ``` The next CSS rule sets the {{cssxref("background-color")}} of all {{HTMLElement("tr")}} elements in the table's head (as specified using {{HTMLElement("thead")}}). Then the bottom border of the head is set to be a two-pixel wide line. Notice, however, that we're using the {{CSSxRef(":nth-of-type")}} selector to apply the {{CSSxRef("border-bottom")}} property to the _second_ row in the head. Why? Because the head is made of two rows that are spanned by some of the cells. That means there are actually two rows there; applying the style to the first row would not give us the expected result: ```css thead > tr { background-color: rgb(228 240 245); } thead > tr:nth-of-type(2) { border-bottom: 2px solid rgb(140 140 140); } ``` Let's style the two header cells "Joined" and "Canceled" with green and red hues to represent the "good" of a new member and the "bummer" of a canceled membership. Here we dig into the last row of the table's head section using the {{CSSxRef(":last-of-type")}} selector and give the first header cell in it (the "Joined" header) a greenish color, and the second header cell in it (the "Canceled" header) a reddish hue: ```css thead > tr:last-of-type > th:nth-of-type(1) { background-color: rgb(225 255 225); } thead > tr:last-of-type > th:nth-of-type(2) { background-color: rgb(255 225 225); } ``` Since the first column should stand out as well, some custom styling is added here too. This CSS rule styles the first header cell in each row of the table's body with the {{CSSxRef("text-align")}} property to left-justify the member names, and with a somewhat different {{cssxref("background-color")}}: ```css tbody > tr > th:first-of-type { text-align: left; background-color: rgb(225 229 244); } ``` It's common to help improve the readability of table data by alternating row colors—this is sometimes referred to as "zebra striping". Let's add a bit of {{cssxref("background-color")}} to every even row: ```css tbody > tr:nth-of-type(even) { background-color: rgb(237 238 242); } ``` Since it's standard practice to right-justify currency values in tables, let's do that here. This just sets the {{CSSxRef("text-align")}} property for the last {{HTMLElement("td")}} in each body row to `right`: ```css tbody > tr > td:last-of-type { text-align: right; } ``` Finally, some styling similar to the head is applied to the foot section of the table to make it stand out as well: ```css tfoot > tr { border-top: 2px dashed rgb(140 140 140); background-color: rgb(228 240 245); } tfoot th, tfoot td { text-align: right; font-weight: bold; } ``` ### Displaying large tables in small spaces A common issue with tables on the web is that they don't natively work very well on small screens when the amount of content is large, and the way to make them scrollable isn't obvious, especially when the markup may come from a CMS and cannot be modified to have a wrapper. This example provides one way to display tables in small spaces. We've hidden the HTML content as it is very large, and there is nothing remarkable about it. The CSS is more useful to inspect in this example. ```html hidden <table> <thead> <tr> <th>1<sup>3</sup> equals: <th>2<sup>3</sup> equals: <th>3<sup>3</sup> equals: <th>4<sup>3</sup> equals: <th>5<sup>3</sup> equals: <th>6<sup>3</sup> equals: <th>7<sup>3</sup> equals: <tbody> <tr> <td>row 1: 1 <td>row 1: 8 <td>row 1: 27 <td>row 1: 64 <td>row 1: 125 <td>row 1: 216 <td>row 1: 343 <tr> <td>row 2: 1 <td>row 2: 8 <td>row 2: 27 <td>row 2: 64 <td>row 2: 125 <td>row 2: 216 <td>row 2: 343 <tr> <td>row 3: 1 <td>row 3: 8 <td>row 3: 27 <td>row 3: 64 <td>row 3: 125 <td>row 3: 216 <td>row 3: 343 <tr> <td>row 4: 1 <td>row 4: 8 <td>row 4: 27 <td>row 4: 64 <td>row 4: 125 <td>row 4: 216 <td>row 4: 343 <tr> <td>row 5: 1 <td>row 5: 8 <td>row 5: 27 <td>row 5: 64 <td>row 5: 125 <td>row 5: 216 <td>row 5: 343 <tr> <td>row 6: 1 <td>row 6: 8 <td>row 6: 27 <td>row 6: 64 <td>row 6: 125 <td>row 6: 216 <td>row 6: 343 <tr> <td>row 7: 1 <td>row 7: 8 <td>row 7: 27 <td>row 7: 64 <td>row 7: 125 <td>row 7: 216 <td>row 7: 343 <tr> <td>row 8: 1 <td>row 8: 8 <td>row 8: 27 <td>row 8: 64 <td>row 8: 125 <td>row 8: 216 <td>row 8: 343 <tr> <td>row 9: 1 <td>row 9: 8 <td>row 9: 27 <td>row 9: 64 <td>row 9: 125 <td>row 9: 216 <td>row 9: 343 <tr> <td>row 10: 1 <td>row 10: 8 <td>row 10: 27 <td>row 10: 64 <td>row 10: 125 <td>row 10: 216 <td>row 10: 343 <tr> <td>row 11: 1 <td>row 11: 8 <td>row 11: 27 <td>row 11: 64 <td>row 11: 125 <td>row 11: 216 <td>row 11: 343 <tr> <td>row 12: 1 <td>row 12: 8 <td>row 12: 27 <td>row 12: 64 <td>row 12: 125 <td>row 12: 216 <td>row 12: 343 <tr> <td>row 13: 1 <td>row 13: 8 <td>row 13: 27 <td>row 13: 64 <td>row 13: 125 <td>row 13: 216 <td>row 13: 343 <tr> <td>row 14: 1 <td>row 14: 8 <td>row 14: 27 <td>row 14: 64 <td>row 14: 125 <td>row 14: 216 <td>row 14: 343 <tr> <td>row 15: 1 <td>row 15: 8 <td>row 15: 27 <td>row 15: 64 <td>row 15: 125 <td>row 15: 216 <td>row 15: 343 <tr> <td>row 16: 1 <td>row 16: 8 <td>row 16: 27 <td>row 16: 64 <td>row 16: 125 <td>row 16: 216 <td>row 16: 343 <tr> <td>row 17: 1 <td>row 17: 8 <td>row 17: 27 <td>row 17: 64 <td>row 17: 125 <td>row 17: 216 <td>row 17: 343 <tr> <td>row 18: 1 <td>row 18: 8 <td>row 18: 27 <td>row 18: 64 <td>row 18: 125 <td>row 18: 216 <td>row 18: 343 <tr> <td>row 19: 1 <td>row 19: 8 <td>row 19: 27 <td>row 19: 64 <td>row 19: 125 <td>row 19: 216 <td>row 19: 343 <tr> <td>row 20: 1 <td>row 20: 8 <td>row 20: 27 <td>row 20: 64 <td>row 20: 125 <td>row 20: 216 <td>row 20: 343 </table> ``` #### CSS When looking at these styles you'll notice that table's {{cssxref("display")}} property has been set to `block`. While this allows scrolling, the table loses some of its integrity, and table cells try to become as small as possible. To mitigate this issue we've set {{cssxref("white-space")}} to `nowrap` on the {{HTMLElement("tbody")}}. However, we don't do this for the {{HTMLElement("thead")}} to avoid long titles forcing columns to be wider than they need to be to display the data. To keep the table headers on the page while scrolling down we've set {{cssxref("position")}} to sticky on the {{HTMLElement("th")}} elements. Note that we have **not** set {{cssxref("border-collapse")}} to `collapse`, as if we do the header cannot be separated correctly from the rest of the table. Given that the `<table>` has a fixed size, the {{cssxref("overflow")}} set to `auto` is the important part here, as it makes the table scrollable. ```css table, th, td { border: 1px solid black; } table { overflow: auto; width: 100%; max-width: 400px; height: 240px; display: block; margin: 0 auto; border-spacing: 0; } tbody { white-space: nowrap; } th, td { padding: 5px 10px; border-top-width: 0; border-left-width: 0; } th { position: sticky; top: 0; background: #fff; vertical-align: bottom; } th:last-child, td:last-child { border-right-width: 0; } tr:last-child td { border-bottom-width: 0; } ``` #### Result {{EmbedLiveSample('Displaying_large_tables_in_small_spaces', '100%', 240)}} ## Accessibility concerns ### Captions By supplying a {{HTMLElement("caption")}} element whose value clearly and concisely describes the table's purpose, it helps the people decide if they need to check the rest of the table content or skip over it. This helps people navigating with the aid of assistive technology such as a screen reader, people experiencing low vision conditions, and people with cognitive concerns. - [MDN Adding a caption to your table with \<caption>](/en-US/docs/Learn/HTML/Tables/Advanced#adding_a_caption_to_your_table_with_caption) - [Caption & Summary • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/caption-summary/) ### Scoping rows and columns The [`scope`](/en-US/docs/Web/HTML/Element/th#scope) attribute on header cells ({{HTMLElement("th")}} elements) is redundant in simple contexts, because scope is inferred. However, some assistive technologies may fail to draw correct inferences, so specifying header scope may improve user experiences. In complex tables, [`scope`](/en-US/docs/Web/HTML/Element/th#scope) can be specified to provide necessary information about the cells related to a header. - [MDN Tables for visually impaired users](/en-US/docs/Learn/HTML/Tables/Advanced#tables_for_visually_impaired_users) - [Tables with two headers • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/two-headers/) - [Tables with irregular headers • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/irregular/) - [H63: Using the scope attribute to associate header cells and data cells in data tables | W3C Techniques for WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/H63.html) ### Complicated tables Assistive technologies such as screen readers may have difficulty parsing tables that are so complex that header cells can't be associated in a strictly horizontal or vertical way. This is typically indicated by the presence of the [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) and [`rowspan`](/en-US/docs/Web/HTML/Element/td#rowspan) attributes. Ideally, consider alternate ways to present the table's content, including breaking it apart into a collection of smaller, related tables that don't have to rely on using the [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) and [`rowspan`](/en-US/docs/Web/HTML/Element/td#rowspan) attributes. In addition to helping people who use assistive technology understand the table's content, this may also benefit people with cognitive concerns who may have difficulty understanding the associations the table layout is describing. If the table cannot be broken apart, use a combination of the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) and [`headers`](/en-US/docs/Web/HTML/Element/td#headers) attributes to programmatically associate each table cell with the header(s) ({{HTMLElement("th")}} elements) the cell is associated with. - [MDN Tables for visually impaired users](/en-US/docs/Learn/HTML/Tables/Advanced#tables_for_visually_impaired_users) - [Tables with multi-level headers • Tables • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/tables/multi-level/) - [H43: Using id and headers attributes to associate data cells with header cells in data tables | Techniques for W3C WCAG 2.0](https://www.w3.org/TR/WCAG20-TECHS/H43.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#flow_content" >Flow content</a > </td> </tr> <tr> <th scope="row">Permitted content</th> <td> In this order: <ol> <li>an optional {{HTMLElement("caption")}} element,</li> <li>zero or more {{HTMLElement("colgroup")}} elements,</li> <li>an optional {{HTMLElement("thead")}} element,</li> <li> either one of the following: <ul> <li>zero or more {{HTMLElement("tbody")}} elements</li> <li>one or more {{HTMLElement("tr")}} elements</li> </ul> </li> <li>an optional {{HTMLElement("tfoot")}} element</li> </ol> </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 flow content</td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Table_Role" >table</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("HTMLTableElement")}}</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("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 the table - {{cssxref("border")}}, {{cssxref("border-collapse")}}, {{cssxref("border-spacing")}}: CSS properties to control the aspect of cell borders, rules, and frame - {{cssxref("margin")}}, {{cssxref("padding")}}: CSS properties to align the table and set spacing on cell content - {{cssxref("text-align")}}: CSS property to horizontally align table cell content - {{cssxref("vertical-align")}}: CSS property to vertically align table cell content - {{cssxref("width")}}: CSS property to control the width of the table
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/template/index.md
--- title: "<template>: The Content Template element" slug: Web/HTML/Element/template page-type: html-element browser-compat: html.elements.template --- {{HTMLSidebar}} The **`<template>`** [HTML](/en-US/docs/Web/HTML) element serves as a mechanism for holding {{Glossary("HTML")}} fragments, which can either be used later via JavaScript or generated immediately into shadow DOM. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `shadowrootmode` - : Creates a [shadow root](/en-US/docs/Glossary/Shadow_tree) for the parent element. It is a declarative version of the {{domxref("Element.attachShadow()")}} method and accepts the same {{glossary("enumerated")}} values. - `open` - : Exposes the internal shadow root DOM for JavaScript (recommended for most use cases). - `closed` - : Hides the internal shadow root DOM from JavaScript. > **Note:** This is a feature of the HTML parser that cannot be used post-parsing by setting the `shadowrootmode` attribute through JavaScript. Only allowed values will create the shadow root; any other values, including empty ones, won't trigger this behavior. > **Note:** You may find the non-standard `shadowroot` attribute in older tutorials and examples that used to be supported in Chrome 90-110. This attribute has since been removed and replaced by the standard `shadowrootmode` attribute. ## Usage notes There are two main ways to use the `<template>` element: 1. By default, the element's content is not rendered, only parsed into a [document fragment](/en-US/docs/Web/API/DocumentFragment). Using the {{domxref("HTMLTemplateElement.content", "content")}} property in JavaScript, this fragment can be cloned via the {{domxref("Node.cloneNode", "cloneNode")}} method and inserted into the DOM. 2. If the element contains the `shadowrootmode` attribute, the HTML parser will immediately generate a shadow DOM. The element is replaced in the DOM by its content wrapped in a [shadow root](/en-US/docs/Glossary/Shadow_tree). The corresponding {{domxref("HTMLTemplateElement")}} interface includes a standard {{domxref("HTMLTemplateElement.content", "content")}} property (without an equivalent content/markup attribute). This `content` property is read-only and holds a {{domxref("DocumentFragment")}} that contains the DOM subtree represented by the template. Be careful when using the `content` property because the returned `DocumentFragment` can exhibit unexpected behavior. For more details, see the [Avoiding DocumentFragment pitfalls](#avoiding_documentfragment_pitfalls) section below. ## Examples ### Generating table rows First we start with the HTML portion of the example. ```html <table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template> ``` First, we have a table into which we will later insert content using JavaScript code. Then comes the template, which describes the structure of an HTML fragment representing a single table row. Now that the table has been created and the template defined, we use JavaScript to insert rows into the table, with each row being constructed using the template as its basis. ```js // Test to see if the browser supports the HTML template element by checking // for the presence of the template element's content attribute. if ("content" in document.createElement("template")) { // Instantiate the table with the existing HTML tbody // and the row with the template const tbody = document.querySelector("tbody"); const template = document.querySelector("#productrow"); // Clone the new row and insert it into the table const clone = template.content.cloneNode(true); let td = clone.querySelectorAll("td"); td[0].textContent = "1235646565"; td[1].textContent = "Stuff"; tbody.appendChild(clone); // Clone the new row and insert it into the table const clone2 = template.content.cloneNode(true); td = clone2.querySelectorAll("td"); td[0].textContent = "0384928528"; td[1].textContent = "Acme Kidney Beans 2"; tbody.appendChild(clone2); } else { // Find another way to add the rows to the table because // the HTML template element is not supported. } ``` The result is the original HTML table, with two new rows appended to it via JavaScript: ```css hidden table { background: #000; } table td { background: #fff; } ``` {{EmbedLiveSample("Table row generation", 500, 120)}} ### Implementing a declarative shadow DOM In this example, a hidden support warning is included at the beginning of the markup. This warning is later set to be displayed via JavaScript if the browser doesn't support the `shadowrootmode` attribute. Next, there are two {{HTMLElement("article")}} elements, each containing nested {{HTMLElement("style")}} elements with different behaviors. The first `<style>` element is global to the whole document. The second one is scoped to the shadow root generated in place of the `<template>` element because of the presence of the `shadowrootmode` attribute. ```html <p hidden> ⛔ Your browser doesn't support <code>shadowrootmode</code> attribute yet. </p> <article> <style> p { padding: 8px; background-color: wheat; } </style> <p>I'm in the DOM.</p> </article> <article> <template shadowrootmode="open"> <style> p { padding: 8px; background-color: plum; } </style> <p>I'm in the shadow DOM.</p> </template> </article> ``` ```js const isShadowRootModeSupported = HTMLTemplateElement.prototype.hasOwnProperty("shadowRootMode"); document .querySelector("p[hidden]") .toggleAttribute("hidden", isShadowRootModeSupported); ``` {{EmbedGHLiveSample("dom-examples/shadow-dom/shadowrootmode/scoping.html", "", "120")}} ## Avoiding DocumentFragment pitfalls When a {{domxref("DocumentFragment")}} value is passed, {{domxref("Node.appendChild")}} and similar methods move only the _child nodes_ of that value into the target node. Therefore, it is usually preferable to attach event handlers to the children of a `DocumentFragment`, rather than to the `DocumentFragment` itself. Consider the following HTML and JavaScript: ### HTML ```html <div id="container"></div> <template id="template"> <div>Click me</div> </template> ``` ### JavaScript ```js const container = document.getElementById("container"); const template = document.getElementById("template"); function clickHandler(event) { event.target.append(" — Clicked this div"); } const firstClone = template.content.cloneNode(true); firstClone.addEventListener("click", clickHandler); container.appendChild(firstClone); const secondClone = template.content.cloneNode(true); secondClone.children[0].addEventListener("click", clickHandler); container.appendChild(secondClone); ``` ### Result Since `firstClone` is a `DocumentFragment`, only its children are added to `container` when `appendChild` is called; the event handlers of `firstClone` are not copied. In contrast, because an event handler is added to the first _child node_ of `secondClone`, the event handler is copied when `appendChild` is called, and clicking on it works as one would expect. {{EmbedLiveSample('Avoiding_DocumentFragment_pitfall')}} ## 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 >, <a href="/en-US/docs/Web/HTML/Content_categories#script-supporting_elements" >script-supporting element</a > </td> </tr> <tr> <th scope="row">Permitted content</th> <td>No restrictions</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 >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, or <a href="/en-US/docs/Web/HTML/Content_categories#script-supporting_elements" >script-supporting elements</a >. Also allowed as a child of a {{HTMLElement("colgroup")}} element that does <em>not</em> 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("HTMLTemplateElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`part`](/en-US/docs/Web/HTML/Global_attributes#part) and [`exportparts`](/en-US/docs/Web/HTML/Global_attributes#exportparts) HTML attributes - {{HTMLElement("slot")}} HTML element - {{CSSXref(":host")}}, {{CSSXref(":host_function", ":host()")}}, and {{CSSXref(":host-context", ":host-context()")}} CSS pseudo-classes - {{CSSXref("::part")}} and {{CSSXref("::slotted")}} CSS pseudo-elements - [`ShadowRoot`]("/en-US/docs/Web/API/ShadowRoot) interface - [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 - [Declarative shadow DOM](https://developer.chrome.com/docs/css-ui/declarative-shadow-dom) on developer.chrome.com (2023)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/plaintext/index.md
--- title: "<plaintext>: The Plain Text element (Deprecated)" slug: Web/HTML/Element/plaintext page-type: html-element status: - deprecated browser-compat: html.elements.plaintext --- {{HTMLSidebar}}{{deprecated_header}} The **`<plaintext>`** [HTML](/en-US/docs/Web/HTML) element renders everything following the start tag as raw text, ignoring any following HTML. There is no closing tag, since everything after it is considered raw text. > **Warning:** Do not use this element. > > - `<plaintext>` is deprecated since HTML 2, and not all browsers implemented it. Browsers that did implement it didn't do so consistently. > - `<plaintext>` is obsolete; browsers that accept it may instead treat it as a {{HTMLElement("pre")}} element that still interprets HTML within. > - If `<plaintext>` is the first element on the page (other than any non-displayed elements, like {{HTMLElement("head")}}), do not use HTML at all. Instead serve a text file with the `text/plain` [MIME-type](/en-US/docs/Learn/Server-side/Configuring_server_MIME_types). > - Instead of `<plaintext>`, use the {{HTMLElement("pre")}} element or, if semantically accurate (such as for inline text), the {{HTMLElement("code")}} element. Escape any `<`, `>` and `&` characters, to prevent browsers inadvertently parsing content the element content as HTML. > - A monospaced font can be applied to any HTML element via a [CSS](/en-US/docs/Web/CSS) {{cssxref("font-family")}} style with the `monospace` generic value. ## Attributes This element has no other attributes than the [global attributes](/en-US/docs/Web/HTML/Global_attributes) common to all elements. ## DOM interface This element implements the {{domxref('HTMLElement')}} interface. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("pre")}} and {{HTMLElement("code")}} elements, which should be used instead. - The {{HTMLElement("xmp")}} element, also obsolete, similar to {{HTMLElement("plaintext")}}.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/ins/index.md
--- title: "<ins>: The Inserted Text element" slug: Web/HTML/Element/ins page-type: html-element browser-compat: html.elements.ins --- {{HTMLSidebar}} The **`<ins>`** [HTML](/en-US/docs/Web/HTML) element represents a range of text that has been added to a document. You can use the {{HTMLElement("del")}} element to similarly represent a range of text that has been deleted from the document. {{EmbedInteractiveExample("pages/tabbed/ins.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `cite` - : This attribute defines the URI of a resource that explains the change, such as a link to meeting minutes or a ticket in a troubleshooting system. - `datetime` - : This attribute indicates the time and date of the change and must be a valid date with an optional time string. 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 [Format of a valid date string](/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 [Format of a valid local date and time string](/en-US/docs/Web/HTML/Date_and_time_formats#local_date_and_time_strings). ## Examples ```html <ins>This text has been inserted</ins> ``` ### Result {{EmbedLiveSample("Examples")}} ## Accessibility concerns The presence of the `<ins>` 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 ins::before, ins::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } ins::before { content: " [insertion start] "; } ins::after { content: " [insertion 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 inserted 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">insertion</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("del")}} element for marking deletion into a document
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/search/index.md
--- title: "<search>: The generic search element" slug: Web/HTML/Element/search page-type: html-element browser-compat: html.elements.search --- {{HTMLSidebar}} The **`<search>`** [HTML](/en-US/docs/Web/HTML) element is a container representing the parts of the document or application with form controls or other content related to performing a search or filtering operation. The `<search>` element semantically identifies the purpose of the element's contents as having search or filtering capabilities. The search or filtering functionality can be for the website or application, the current web page or document, or the entire Internet or subsection thereof. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<search>` element is not for presenting search results. Rather, search or filtered results should be presented as part of the main content of that web page. That said, suggestions and links that are part of "quick search" functionality within the search or filtering functionality are appropriately nested within the contents of the `<search>` element as they are search features. ## Accessibility concerns The `<search>` element defines a [`search`](/en-US/docs/Web/Accessibility/ARIA/Roles/search_role) landmark. This removes the need for adding `role=search` to a {{HTMLElement('form')}} element. ## Examples ### Header search form This example demonstrates the use of `<search>` as the container for a search within a website header to perform a simple site-wide search. The `<search>` is a semantic container for the {{HTMLElement("form")}} that submits the user-entered search query to a server. #### HTML ```html <header> <h1>Movie website</h1> <search> <form action="./search/"> <label for="movie">Find a Movie</label> <input type="search" id="movie" name="q" /> <button type="submit">Search</button> </form> </search> </header> ``` #### Result {{EmbedLiveSample('Header search form')}} ### Web app search This example demonstrates potential DOM content when dynamically including JavaScript search functionality in a web application. When search functionality is implemented entirely with JavaScript, if no form is submitted, neither a {{HTMLElement("form")}} element nor a submit {{HTMLElement("button")}} is required. For semantics, the `<search>` element is included to contain the search and filtering capabilities. #### HTML ```html <search> <label> Find and filter your query <input type="search" id="query" /> </label> <label> <input type="checkbox" id="exact-only" /> Exact matches only </label> <section> <h3>Results:</h3> <ul id="results"> <!-- search result content --> </ul> <output id="no-results"> <!-- no results content --> </output> </section> </search> ``` #### Result {{EmbedLiveSample('Web app search')}} > **Note:** Remember that some users don't have JavaScript, and none of your users have JavaScript running until the JavaScript is successfully downloaded, parsed, and executed, ensure your users can access the content of your site with JavaScript disabled. ### Multiple searches This example demonstrates a page with two search features. The first is a global site search located on the header. The second is a search and filter based on the page context, in our example a car search. #### HTML ```html <body> <header> <h1>Car rental agency</h1> <search title="Website">...</search> </header> <main> <h2>Cars available for rent</h2> <search title="Cars"> <h3>Filter results</h3> ... </search> <article> <!-- search result content --> </article> </main> </body> ``` #### Result {{EmbedLiveSample('Multiple searches')}} ## 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#palpable_content">palpable content</a>. </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>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/search_role">search</a></code> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/form_role"><code>form</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/region_role"><code>region</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/search_role"><code>search</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other search-related elements: {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("aside")}}, {{HTMLElement("nav")}}, {{HTMLElement("form")}} - [ARIA: Search role](/en-US/docs/Web/Accessibility/ARIA/Roles/search_role)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/p/index.md
--- title: "<p>: The Paragraph element" slug: Web/HTML/Element/p page-type: html-element browser-compat: html.elements.p --- {{HTMLSidebar}} The **`<p>`** [HTML](/en-US/docs/Web/HTML) element represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields. Paragraphs are [block-level elements](/en-US/docs/Glossary/Block-level_content), and notably will automatically close if another block-level element is parsed before the closing `</p>` tag. See "Tag omission" below. {{EmbedInteractiveExample("pages/tabbed/p.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). > **Note:** The `align` attribute on `<p>` tags is obsolete and shouldn't be used. ## Examples ### HTML ```html <p> This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. </p> <p> This is the second paragraph. This is the second paragraph. This is the second paragraph. This is the second paragraph. </p> ``` ### Result {{EmbedLiveSample('Examples')}} ## Styling paragraphs By default, browsers separate paragraphs with a single blank line. Alternate separation methods, such as first-line indentation, can be achieved with {{glossary("CSS")}}: ### HTML ```html <p> Separating paragraphs with blank lines is easiest for readers to scan, but they can also be separated by indenting their first lines. This is often used to take up less space, such as to save paper in print. </p> <p> Writing that is intended to be edited, such as school papers and rough drafts, uses both blank lines and indentation for separation. In finished works, combining both is considered redundant and amateurish. </p> <p> In very old writing, paragraphs were separated with a special character: ¶, the <i>pilcrow</i>. Nowadays, this is considered claustrophobic and hard to read. </p> <p> How hard to read? See for yourself: <button data-toggle-text="Oh no! Switch back!"> Use pilcrow for paragraphs </button> </p> ``` ### CSS ```css p { margin: 0; text-indent: 3ch; } p.pilcrow { text-indent: 0; display: inline; } p.pilcrow + p.pilcrow::before { content: " ¶ "; } ``` ### JavaScript ```js document.querySelector("button").addEventListener("click", (event) => { document.querySelectorAll("p").forEach((paragraph) => { paragraph.classList.toggle("pilcrow"); }); [event.target.innerText, event.target.dataset.toggleText] = [ event.target.dataset.toggleText, event.target.innerText, ]; }); ``` ### Result {{EmbedLiveSample('Styling_paragraphs')}} ## Accessibility concerns Breaking up content into paragraphs helps make a page more accessible. Screen-readers and other assistive technology provide shortcuts to let their users skip to the next or previous paragraph, letting them skim content like how white space lets visual users skip around. Using empty `<p>` elements to add space between paragraphs is problematic for people who navigate with screen-reading technology. Screen readers may announce the paragraph's presence, but not any content contained within it — because there is none. This can confuse and frustrate the person using the screen reader. If extra space is desired, use {{glossary("CSS")}} properties like {{cssxref("margin")}} to create the effect: ```css p { margin-bottom: 2em; /* increase white space after a paragraph */ } ``` ## 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 >, 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> The start tag is required. The end tag may be omitted if the {{HTMLElement("p")}} element is immediately followed by an {{HTMLElement("address")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("blockquote")}}, {{HTMLElement("details")}}, {{HTMLElement("div")}}, {{HTMLElement("dl")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("figure")}}, {{HTMLElement("footer")}}, {{HTMLElement("form")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}, {{HTMLElement("header")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("hr")}}, {{HTMLElement("main")}}, {{HTMLElement("menu")}}, {{HTMLElement("nav")}}, {{HTMLElement("ol")}}, {{HTMLElement("pre")}}, {{HTMLElement("search")}}, {{HTMLElement("section")}}, {{HTMLElement("table")}}, {{HTMLElement("ul")}} or another {{HTMLElement("p")}} element, or if there is no more content in the parent element and the parent element is not an {{HTMLElement("a")}}, {{HTMLElement("audio")}}, {{HTMLElement("del")}}, {{HTMLElement("ins")}}, {{HTMLElement("map")}}, {{HTMLElement("noscript")}} or {{HTMLElement("video")}} element, or an autonomous custom element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> 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> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles" >paragraph</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLParagraphElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("hr")}} - {{HTMLElement("br")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/div/index.md
--- title: "<div>: The Content Division element" slug: Web/HTML/Element/div page-type: html-element browser-compat: html.elements.div --- {{HTMLSidebar}} The **`<div>`** [HTML](/en-US/docs/Web/HTML) element is the generic container for flow content. It has no effect on the content or layout until styled in some way using {{glossary("CSS")}} (e.g. styling is directly applied to it, or some kind of layout model like [Flexbox](/en-US/docs/Web/CSS/CSS_flexible_box_layout) is applied to its parent element). {{EmbedInteractiveExample("pages/tabbed/div.html","tabbed-standard")}} As a "pure" container, the `<div>` element does not inherently represent anything. Instead, it's used to group content so it can be easily styled using the [`class`](/en-US/docs/Web/HTML/Global_attributes#class) or [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attributes, marking a section of a document as being written in a different language (using the [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang) attribute), and so on. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). > **Note:** The `align` attribute is obsolete; do not use it anymore. Instead, you should use CSS properties or techniques such as [CSS Grid](/en-US/docs/Web/CSS/CSS_grid_layout) or [CSS Flexbox](/en-US/docs/Learn/CSS/CSS_layout/Flexbox) to align and position `<div>` elements on the page. ## Usage notes - The `<div>` element should be used only when no other semantic element (such as {{HTMLElement("article")}} or {{HTMLElement("nav")}}) is appropriate. ## Examples ### A simple example ```html <div> <p> Any kind of content here. Such as &lt;p&gt;, &lt;table&gt;. You name it! </p> </div> ``` #### Result {{EmbedLiveSample("A_simple_example", 650, 60)}} ### A styled example This example creates a shadowed box by applying a style to the `<div>` using CSS. Note the use of the [`class`](/en-US/docs/Web/HTML/Global_attributes#class) attribute on the `<div>` to apply the style named `"shadowbox"` to the element. #### HTML ```html <div class="shadowbox"> <p>Here's a very interesting note displayed in a lovely shadowed box.</p> </div> ``` #### CSS ```css .shadowbox { width: 15em; border: 1px solid #333; box-shadow: 8px 8px 5px #444; padding: 8px 12px; background-image: linear-gradient(180deg, #fff, #ddd 40%, #ccc); } ``` #### Result {{EmbedLiveSample("A_styled_example", 650, 120)}} ## Accessibility concerns The `<div>` element has [an implicit role of `generic`](https://www.w3.org/TR/wai-aria-1.2/#generic), and not none. This may affect certain ARIA combination declarations that expect a direct descendant element with a certain role to function properly. ## 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#palpable_content">palpable content</a>. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >.<br />Or (in {{glossary("WHATWG")}} HTML): If the parent is a {{HTMLElement("dl")}} element: one or more {{HTMLElement("dt")}} elements followed by one or more {{HTMLElement("dd")}} elements, optionally intermixed with {{HTMLElement("script")}} and {{HTMLElement("template")}} elements. </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#flow_content" >flow content</a >.<br />Or (in {{glossary("WHATWG")}} HTML): {{HTMLElement("dl")}} element. </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("HTMLDivElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Semantic sectioning elements: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} - {{HTMLElement("span")}} element for styling of phrasing content
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/i/index.md
--- title: "<i>: The Idiomatic Text element" slug: Web/HTML/Element/i page-type: html-element browser-compat: html.elements.i --- {{HTMLSidebar}} The **`<i>`** [HTML](/en-US/docs/Web/HTML) element represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the `<i>` naming of this element. {{EmbedInteractiveExample("pages/tabbed/i.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Use the `<i>` element for text that is set off from the normal prose for readability reasons. This would be a range of text with different semantic meaning than the surrounding text. Among the use cases for the `<i>` element are spans of text representing a different quality or mode of text, such as: - Alternative voice or mood - Taxonomic designations (such as the genus and species "_Homo sapiens_") - Idiomatic terms from another language (such as "_et cetera_"); these should include the [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang) attribute to identify the language - Technical terms - Transliterations - Thoughts (such as "She wondered, _What is this writer talking about, anyway?_") - Ship or vessel names in Western writing systems (such as "They searched the docks for the _Empress of the Galaxy_, the ship to which they were assigned.") - In earlier versions of the HTML specification, the `<i>` element was merely a presentational element used to display text in italics, much like the `<b>` element was used to display text in bold letters. This is no longer true, as these tags now define semantics rather than typographic appearance. A browser will typically still display the contents of the `<i>` element in italic type, but is, by definition, no longer required to do so. To display text in italic type, authors should use the CSS {{cssxref("font-style")}} property. - Be sure the text in question is not actually more appropriately marked up with another element. - Use {{HTMLElement("em")}} to indicate stress emphasis. - Use {{HTMLElement("strong")}} to indicate importance, seriousness, or urgency. - Use {{HTMLElement("mark")}} to indicate relevance. - Use {{HTMLElement("cite")}} to mark up the name of a work, such as a book, play, or song. - Use {{HTMLElement("dfn")}} to mark up the defining instance of a term. ## Examples This example demonstrates using the `<i>` element to mark text that is in another language. ```html <p> The Latin phrase <i lang="la">Veni, vidi, vici</i> is often mentioned in music, art, and literature. </p> ``` ### Result {{EmbedLiveSample("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> <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("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("em")}} - Other italicized elements: {{HTMLElement("var")}}, {{HTMLElement("dfn")}}, {{HTMLElement("cite")}}, {{HTMLElement("address")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/embed/index.md
--- title: "<embed>: The Embed External Content element" slug: Web/HTML/Element/embed page-type: html-element browser-compat: html.elements.embed --- {{HTMLSidebar}} The **`<embed>`** [HTML](/en-US/docs/Web/HTML) element embeds external content at the specified point in the document. This content is provided by an external application or other source of interactive content such as a browser plug-in. {{EmbedInteractiveExample("pages/tabbed/embed.html", "tabbed-standard")}} > **Note:** This topic documents only the element that is defined as part of the [HTML Living Standard](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-embed-element). It does not address earlier, non-standardized implementation of the element. Keep in mind that most modern browsers have deprecated and removed support for browser plug-ins, so relying upon `<embed>` is generally not wise if you want your site to be operable on the average user's browser. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `height` - : The displayed height of the resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). This must be an absolute value; percentages are _not_ allowed. - `src` - : The URL of the resource being embedded. - `type` - : The {{glossary("MIME type")}} to use to select the plug-in to instantiate. - `width` - : The displayed width of the resource, in [CSS pixels](https://drafts.csswg.org/css-values/#px). This must be an absolute value; percentages are _not_ allowed. ## Usage notes You can use the {{cssxref("object-position")}} property to adjust the positioning of the embedded object within the element's frame, and the {{cssxref("object-fit")}} property to control how the object's size is adjusted to fit within the frame. ## Examples ```html <embed type="video/quicktime" src="movie.mov" width="640" height="480" title="Title of my video" /> ``` ## Accessibility concerns Use the [`title` attribute](/en-US/docs/Web/HTML/Global_attributes/title) on an `embed` element to label its content so that people navigating with assistive technology such as a screen reader can understand what it contains. The title's value should concisely describe the embedded content. Without a title, they may not be able to determine what its embedded content is. This context shift can be confusing and time-consuming, especially if the `embed` element contains interactive content like video or audio. ## 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 >, embedded content, interactive content, <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content" >palpable content</a >. </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> <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>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLEmbedElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other elements that are used for embedding content of various types include {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{MathMLElement("math")}}, {{HTMLElement("object")}}, {{SVGElement("svg")}}, and {{HTMLElement("video")}}. - Positioning and sizing the embedded content within its frame: {{cssxref("object-position")}} and {{cssxref("object-fit")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/base/index.md
--- title: "<base>: The Document Base URL element" slug: Web/HTML/Element/base page-type: html-element browser-compat: html.elements.base --- {{HTMLSidebar}} The **`<base>`** [HTML](/en-US/docs/Web/HTML) element specifies the base URL to use for all _relative_ URLs in a document. There can be only one `<base>` element in a document. A document's used base URL can be accessed by scripts with {{domxref('Node.baseURI')}}. If the document has no `<base>` elements, then `baseURI` defaults to {{domxref("location.href")}}. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). > **Warning:** A `<base>` element must have an `href` attribute, a `target` attribute, or both. > If at least one of these attributes are specified, the `<base>` element **must** come before other elements with attribute values that are URLs, such as a {{HTMLElement("link")}}'s `href` attribute. - `href` - : The base URL to be used throughout the document for relative URLs. Absolute and relative URLs are allowed. [`data:`](/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) and `javascript:` URLs are not allowed. - `target` - : A **keyword** or **author-defined name** of the default {{Glossary("browsing context")}} to show the results of navigation from {{HTMLElement("a")}}, {{HTMLElement("area")}}, or {{HTMLElement("form")}} elements without explicit `target` attributes. The following keywords have special meanings: - `_self` (default): Show the result in the current browsing context. - `_blank`: Show the result in a new, unnamed browsing context. - `_parent`: Show the result in the parent browsing context of the current one, if the current page is inside a frame. If there is no parent, acts the same as `_self`. - `_top`: Show the result in the topmost browsing context (the browsing context that is an ancestor of the current one and has no parent). If there is no parent, acts the same as `_self`. ## Usage notes ### Multiple \<base> elements If multiple `<base>` elements are used, only the first `href` and first `target` are obeyed — all others are ignored. ### In-page anchors Links pointing to a fragment in the document — e.g. `<a href="#some-id">` — are resolved with the `<base>`, triggering an HTTP request to the base URL with the fragment attached. For example, given `<base href="https://example.com/">` and this link: `<a href="#anchor">To anchor</a>`. The link points to `https://example.com/#anchor`. ### Open Graph [Open Graph](https://ogp.me/) tags do not acknowledge `<base>`, and should always have full absolute URLs. For example: ```html <meta property="og:image" content="https://example.com/thumbnail.jpg" /> ``` ## Examples ```html <base href="https://www.example.com/" /> <base target="_blank" /> <base target="_top" href="https://example.com/" /> ``` ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a> </th> <td>Metadata content.</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>There must be no closing tag.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("head")}} that doesn't contain another {{HTMLElement("base")}} 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("HTMLBaseElement")}}</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/fieldset/index.md
--- title: "<fieldset>: The Field Set element" slug: Web/HTML/Element/fieldset page-type: html-element browser-compat: html.elements.fieldset --- {{HTMLSidebar}} The **`<fieldset>`** [HTML](/en-US/docs/Web/HTML) element is used to group several controls as well as labels ({{HTMLElement("label")}}) within a web form. {{EmbedInteractiveExample("pages/tabbed/fieldset.html", "tabbed-standard")}} As the example above shows, the `<fieldset>` element provides a grouping for a part of an HTML form, with a nested {{htmlelement("legend")}} element providing a caption for the `<fieldset>`. It takes few attributes, the most notable of which are `form`, which can contain the `id` of a {{htmlelement("form")}} on the same page, allowing you to make the `<fieldset>` part of that `<form>` even if it is not nested inside it, and `disabled`, which allows you to disable the `<fieldset>` and all its contents in one go. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `disabled` - : If this Boolean attribute is set, all form controls that are descendants of the `<fieldset>`, are disabled, meaning they are not editable and won't be submitted along with the {{htmlelement("form")}}. They won't receive any browsing events, like mouse clicks or focus-related events. By default browsers display such controls grayed out. Note that form elements inside the {{HTMLElement("legend")}} element won't be disabled. - `form` - : This attribute takes the value of the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute of a {{HTMLElement("form")}} element you want the `<fieldset>` to be part of, even if it is not inside the form. Please note that usage of this is confusing — if you want the {{HTMLElement("input")}} elements inside the `<fieldset>` to be associated with the form, you need to use the `form` attribute directly on those elements. You can check which elements are associated with a form via JavaScript, using {{domxref("HTMLFormElement.elements")}}. - `name` - : The name associated with the group. > **Note:** The caption for the fieldset is given by the first {{HTMLElement("legend")}} element nested inside it. ## Styling with CSS There are several special styling considerations for `<fieldset>`. Its {{cssxref("display")}} value is `block` by default, and it establishes a [block formatting context](/en-US/docs/Web/CSS/CSS_display/Block_formatting_context). If the `<fieldset>` is styled with an inline-level `display` value, it will behave as `inline-block`, otherwise it will behave as `block`. By default there is a `2px` `groove` border surrounding the contents, and a small amount of default padding. The element has {{cssxref("min-inline-size", "min-inline-size: min-content")}} by default. If a {{htmlelement("legend")}} is present, it is placed over the `block-start` border. The `<legend>` shrink-wraps, and also establishes a formatting context. The `display` value is blockified. (For example, `display: inline` behaves as `block`.) There will be an anonymous box holding the contents of the `<fieldset>`, which inherits certain properties from the `<fieldset>`. If the `<fieldset>` is styled with `display: grid` or `display: inline-grid`, then the anonymous box will be a grid formatting context. If the `<fieldset>` is styled with `display: flex` or `display: inline-flex`, then the anonymous box will be a flex formatting context. Otherwise, it establishes a block formatting context. You can feel free to style the `<fieldset>` and `<legend>` in any way you want to suit your page design. ## Examples ### Simple fieldset This example shows a really simple `<fieldset>` example, with a `<legend>`, and a single control inside it. ```html <form action="#"> <fieldset> <legend>Do you agree?</legend> <input type="checkbox" id="chbx" name="agree" value="Yes!" /> <label for="chbx">I agree</label> </fieldset> </form> ``` #### Result {{ EmbedLiveSample('Simple_fieldset', '100%', '80') }} ### Disabled fieldset This example shows a disabled `<fieldset>` with two controls inside it. Note how both the controls are disabled due to being inside a disabled `<fieldset>`. ```html <form action="#"> <fieldset disabled> <legend>Disabled login fieldset</legend> <div> <label for="name">Name: </label> <input type="text" id="name" value="Chris" /> </div> <div> <label for="pwd">Archetype: </label> <input type="password" id="pwd" value="Wookie" /> </div> </fieldset> </form> ``` #### Result {{ EmbedLiveSample('Disabled_fieldset', '100%', '110') }} ## 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/Element/Heading_Elements#sectioning_root" >sectioning root</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form_listed" >listed</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form-associated_content" >form-associated</a > element, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> An optional {{HTMLElement("legend")}} element, followed by flow content. </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#flow_content" >flow content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></a></td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role"><code>radiogroup</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLFieldSetElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("legend")}} element - The {{HTMLElement("input")}} element - The {{HTMLElement("label")}} element - The {{HTMLElement("form")}} element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/acronym/index.md
--- title: <acronym> slug: Web/HTML/Element/acronym page-type: html-element status: - deprecated browser-compat: html.elements.acronym --- {{HTMLSidebar}}{{deprecated_header}} The **`<acronym>`** [HTML](/en-US/docs/Web/HTML) element allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. > **Warning:** Don't use this element. Use the {{HTMLElement("abbr")}} element instead. ## Attributes This element only has [global attributes](/en-US/docs/Web/HTML/Global_attributes), which are common to all elements. ## DOM Interface This element implements the {{domxref('HTMLElement')}} interface. ## Examples ```html <p> The <acronym title="World Wide Web">WWW</acronym> is only a component of the Internet. </p> ``` ### Result {{EmbedLiveSample('Examples')}} ## Default styling Though the purpose of this tag is purely for the convenience of the author, its default styling varies from one browser to another: - Opera, Firefox, Chrome, and some others add a dotted underline to the content of the element. - A few browsers not only add a dotted underline, but also put it in small caps; to avoid this styling, adding something like {{cssxref('font-variant')}}`: none` in the CSS takes care of this case. It is therefore recommended that web authors either explicitly style this element, or accept some cross-browser variation. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("abbr")}} HTML element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/tfoot/index.md
--- title: "<tfoot>: The Table Foot element" slug: Web/HTML/Element/tfoot page-type: html-element browser-compat: html.elements.tfoot --- {{HTMLSidebar}} The **`<tfoot>`** [HTML](/en-US/docs/Web/HTML) element encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the foot of a table with information about the table's columns. This is usually a summary of the columns, e.g., a sum of the given numbers in a column. {{EmbedInteractiveExample("pages/tabbed/tfoot.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 foot 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 foot 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 foot 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 foot cell content from the alignment character specified by the [`char`](#char) attribute. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of each foot 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 `<tfoot>` is placed after any {{HTMLElement("caption")}}, {{HTMLElement("colgroup")}}, {{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, and {{HTMLElement("tr")}} elements. - Along with its related {{HTMLElement("thead")}} and {{HTMLElement("tbody")}} elements, the `<tfoot>` element provides useful {{Glossary("semantics", "semantic")}} information and can be used when rendering for either screen or print. Specifying such table content groups also provides valuable contextual information for assistive technologies, including screen readers and search engines. - When printing a document, in the case of a multipage table, the table foot usually specifies information that is output as an intermediate summary on each page. ## Example See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. This example demonstrates a table divided into a head section with column headers, a body section with the table's main data, and a foot section summarizing data of one column. #### HTML The {{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, and `<tfoot>` elements are used to structure a basic table into {{Glossary("semantics", "semantic")}} sections. The `<tfoot>` element represents the foot section of the table, which contains a row ({{HTMLElement("tr")}}) representing the calculated average of the values in the "Credits" column. To allocate the cells in the foot to the correct columns, the [`colspan`](/en-US/docs/Web/HTML/Element/th#colspan) attribute is used on the {{HTMLElement("th")}} element to span row header cell across the first three table columns. The single data cell ({{HTMLElement("td")}}) in the foot is automatically placed in the correct location, i.e., the fourth column, with the omitted [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute value defaulting to `1`. Additionally, the [`scope`](/en-US/docs/Web/HTML/Element/th#scope) attribute is set to `row` on the header cell ({{HTMLElement("th")}}) in the foot to explicitly define that this foot header cell relates to the table cells within the same row, which in our example is the one data cell in the foot row that contains the calculated average. ```html <table> <thead> <tr> <th>Student ID</th> <th>Name</th> <th>Major</th> <th>Credits</th> </tr> </thead> <tbody> <tr> <td>3741255</td> <td>Jones, Martha</td> <td>Computer Science</td> <td>240</td> </tr> <tr> <td>3971244</td> <td>Nim, Victor</td> <td>Russian Literature</td> <td>220</td> </tr> <tr> <td>4100332</td> <td>Petrov, Alexandra</td> <td>Astrophysics</td> <td>260</td> </tr> </tbody> <tfoot> <tr> <th colspan="3" scope="row">Average Credits</th> <td>240</td> </tr> </tfoot> </table> ``` #### CSS Some basic CSS is used to style and highlight the table foot so that the foot cells stand out from the data in the table body. ```css tfoot { border-top: 3px dotted rgb(160 160 160); background-color: #2c5e77; color: #fff; } tfoot th { text-align: right; } tfoot td { font-weight: bold; } thead { border-bottom: 2px solid rgb(160 160 160); background-color: #2c5e77; color: #fff; } tbody { background-color: #e4f0f5; } ``` ```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; } tr > td:last-of-type { text-align: center; } ``` #### Result {{EmbedLiveSample("Example", 650, 180)}} ## 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("tr")}} elements.</td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is mandatory. The end tag may be omitted if there is no more content in the parent {{HTMLElement("table")}} element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("table")}} element. The {{HTMLElement("tfoot")}} must appear after any {{HTMLElement("caption")}}, {{HTMLElement("colgroup")}}, {{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, and {{HTMLElement("tr")}} elements. Note that this is the requirement in HTML.<br />Originally, in HTML4, the opposite was true: the {{HTMLElement("tfoot")}} element could not be placed after any {{HTMLElement("tbody")}} and {{HTMLElement("tr")}} elements. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Rowgroup_Role" >rowgroup</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("HTMLTableSectionElement")}}</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("th")}}, {{HTMLElement("thead")}}, {{HTMLElement("tr")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each foot cell - {{cssxref("border")}}: CSS property to control borders of foot cells - {{cssxref("text-align")}}: CSS property to horizontally align each foot cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each foot cell content
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/meter/index.md
--- title: "<meter>: The HTML Meter element" slug: Web/HTML/Element/meter page-type: html-element browser-compat: html.elements.meter --- {{HTMLSidebar}} The **`<meter>`** [HTML](/en-US/docs/Web/HTML) element represents either a scalar value within a known range or a fractional value. {{EmbedInteractiveExample("pages/tabbed/meter.html", "tabbed-shorter")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `value` - : The current numeric value. This must be between the minimum and maximum values (`min` attribute and `max` attribute) if they are specified. If unspecified or malformed, the value is `0`. If specified, but not within the range given by the `min` attribute and `max` attribute, the value is equal to the nearest end of the range. > **Note:** Unless the `value` attribute is between `0` and `1` (inclusive), the `min` and `max` attributes should define the range so that the `value` attribute's value is within it. - `min` - : The lower numeric bound of the measured range. This must be less than the maximum value (`max` attribute), if specified. If unspecified, the minimum value is `0`. - `max` - : The upper numeric bound of the measured range. This must be greater than the minimum value (`min` attribute), if specified. If unspecified, the maximum value is `1`. - `low` - : The upper numeric bound of the low end of the measured range. This must be greater than the minimum value (`min` attribute), and it also must be less than the high value and maximum value (`high` attribute and `max` attribute, respectively), if any are specified. If unspecified, or if less than the minimum value, the `low` value is equal to the minimum value. - `high` - : The lower numeric bound of the high end of the measured range. This must be less than the maximum value (`max` attribute), and it also must be greater than the low value and minimum value (`low` attribute and `min` attribute, respectively), if any are specified. If unspecified, or if greater than the maximum value, the `high` value is equal to the maximum value. - `optimum` - : This attribute indicates the optimal numeric value. It must be within the range (as defined by the `min` attribute and `max` attribute). When used with the `low` attribute and `high` attribute, it gives an indication where along the range is considered preferable. For example, if it is between the `min` attribute and the `low` attribute, then the lower range is considered preferred. The browser may color the meter's bar differently depending on whether the value is less than or equal to the optimum value. - `form` - : This optional attribute is used to explicitly set a {{HTMLElement("form")}} owner for the `<meter>` element. If omitted, the `<meter>` is associated with its ancestor `<form>` element or the form association set by the `form` attribute on another ancestor element, such as on a {{HTMLElement("fieldset")}}, if any. If included, the value must be the [`id`](/en-US/docs/Web/HTML/Global_attributes/id) of a `<form>` in the same tree. ## Examples ### Simple example #### HTML ```html <p> Heat the oven to <meter min="200" max="500" value="350">350 degrees</meter>. </p> ``` #### Result {{EmbedLiveSample("Simple_example", 300, 60)}} On Google Chrome, the resulting meter looks like this: ![A screenshot of the meter element in Google Chrome](screen_shot_2020-10-12_at_10.10.53_pm.png) ### High and Low range example Note that in this example the [`min`](#min) attribute is omitted. This is allowed, as it will default to `0`. #### HTML ```html <p> He got a <meter low="69" high="80" max="100" value="84">B</meter> on the exam. </p> ``` #### Result {{EmbedLiveSample("High_and_Low_range_example", 300, 60)}} On Google Chrome, the resulting meter looks like this: ![red meter in Google Chrome](screen_shot_2020-10-12_at_10.11.52_pm.png) ## 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 >, labelable content, 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 >, but there must be no <code>&#x3C;meter></code> element among its descendants. </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">meter</a ></code > </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("HTMLMeterElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("progress")}} - {{cssxref("::-webkit-meter-bar")}}, {{cssxref("::-webkit-meter-inner-element") }}, {{cssxref("::-webkit-meter-even-less-good-value")}}, {{cssxref("::-webkit-meter-optimum-value")}}, {{cssxref("::-webkit-meter-suboptimum-value")}}: non-standard pseudo-elements
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/textarea/index.md
--- title: "<textarea>: The Textarea element" slug: Web/HTML/Element/textarea page-type: html-element browser-compat: html.elements.textarea --- {{HTMLSidebar}} The **`<textarea>`** [HTML](/en-US/docs/Web/HTML) element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form. {{EmbedInteractiveExample("pages/tabbed/textarea.html", "tabbed-standard")}} The above example demonstrates a number of features of `<textarea>`: - An `id` attribute to allow the `<textarea>` to be associated with a {{htmlelement("label")}} element for accessibility purposes - A `name` attribute to set the name of the associated data point submitted to the server when the form is submitted. - `rows` and `cols` attributes to allow you to specify an exact size for the `<textarea>` to take. Setting these is a good idea for consistency, as browser defaults can differ. - Default content entered between the opening and closing tags. `<textarea>` does not support the `value` attribute. The `<textarea>` element also accepts several attributes common to form `<input>`s, such as `autocapitalize`, `autocomplete`, `autofocus`, `disabled`, `placeholder`, `readonly`, and `required`. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `autocapitalize` - : Controls whether inputted text is automatically capitalized and, if so, in what manner. See the [`autocapitalize`](/en-US/docs/Web/HTML/Global_attributes/autocapitalize) global attribute page for more information. - `autocomplete` - : This attribute indicates whether the value of the control can be automatically completed by the browser. Possible values are: - `off`: The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry. - `on`: The browser can automatically complete the value based on values that the user has entered during previous uses. If the `autocomplete` attribute is not specified on a `<textarea>` element, then the browser uses the `autocomplete` attribute value of the `<textarea>` element's form owner. The form owner is either the {{HTMLElement("form")}} element that this `<textarea>` element is a descendant of or the form element whose `id` is specified by the `form` attribute of the input element. For more information, see the [`autocomplete`](/en-US/docs/Web/HTML/Element/form#autocomplete) attribute in {{HTMLElement("form")}}. - `autocorrect` {{non-standard_inline}} - : A string which indicates whether to activate automatic spelling correction and processing of text substitutions (if any are configured) while the user is editing this `textarea`. Permitted values are: - `on` - : Enable automatic spelling correction and text substitutions. - `off` - : Disable automatic spelling correction and text substitutions. - `autofocus` - : This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form-associated element in a document can have this attribute specified. - `cols` - : The visible width of the text control, in average character widths. If it is specified, it must be a positive integer. If it is not specified, the default value is `20`. - `dirname` - : This attribute is used to indicate the text directionality of the element contents similar to the [`dirname`](/en-US/docs/Web/HTML/Element/input#dirname) attribute of the `<input>` element. For more information, see the [`dirname` attribute](/en-US/docs/Web/HTML/Attributes/dirname). - `disabled` - : This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example {{ HTMLElement("fieldset") }}; if there is no containing element when the `disabled` attribute is set, the control is enabled. - `form` - : The form element that the `<textarea>` element is associated with (its "form owner"). The value of the attribute must be the `id` of a form element in the same document. If this attribute is not specified, the `<textarea>` element must be a descendant of a form element. This attribute enables you to place `<textarea>` elements anywhere within a document, not just as descendants of form elements. - `maxlength` - : The maximum string length (measured in UTF-16 code units) that the user can enter. If this value isn't specified, the user can enter an unlimited number of characters. - `minlength` - : The minimum string length (measured in UTF-16 code units) required that the user should enter. - `name` - : The name of the control. - `placeholder` - : A hint to the user of what can be entered in the control. Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint. > **Note:** Placeholders should only be used to show an example of the type of data that should be entered into a form; they are _not_ a substitute for a proper {{HTMLElement("label")}} element tied to the input. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for a full explanation. - `readonly` - : This Boolean attribute indicates that the user cannot modify the value of the control. Unlike the `disabled` attribute, the `readonly` attribute does not prevent the user from clicking or selecting in the control. The value of a read-only control is still submitted with the form. - `required` - : This attribute specifies that the user must fill in a value before submitting a form. - `rows` - : The number of visible text lines for the control. If it is specified, it must be a positive integer. If it is not specified, the default value is 2. - `spellcheck` - : Specifies whether the `<textarea>` is subject to spell checking by the underlying browser/OS. The value can be: - `true`: Indicates that the element needs to have its spelling and grammar checked. - `default` : Indicates that the element is to act according to a default behavior, possibly based on the parent element's own `spellcheck` value. - `false` : Indicates that the element should not be spell checked. - `wrap` - : Indicates how the control should wrap the value for form submission. Possible values are: - `hard`: The browser automatically inserts line breaks (CR+LF) so that each line is no longer than the width of the control; the [`cols`](#cols) attribute must be specified for this to take effect - `soft`: The browser ensures that all line breaks in the entered value are a `CR+LF` pair, but no additional line breaks are added to the value. - `off` {{non-standard_inline}}: Like `soft` but changes appearance to `white-space: pre` so line segments exceeding `cols` are not wrapped and the `<textarea>` becomes horizontally scrollable. If this attribute is not specified, `soft` is its default value. ## Styling with CSS `<textarea>` is a [replaced element](/en-US/docs/Web/CSS/Replaced_element) — it has intrinsic dimensions, like a raster image. By default, its {{cssxref("display")}} value is `inline-block`. Compared to other form elements it is relatively easy to style, with its box model, fonts, color scheme, etc. being easily manipulable using regular CSS. [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms) provides some useful tips on styling `<textarea>`s. ### Baseline inconsistency The HTML specification doesn't define where the baseline of a `<textarea>` is, so different browsers set it to different positions. For Gecko, the `<textarea>` baseline is set on the baseline of the first line of the textarea, on another browser it may be set on the bottom of the `<textarea>` box. Don't use {{cssxref("vertical-align")}}`: baseline` on it; the behavior is unpredictable. ### Controlling whether a textarea is resizable In most browsers, `<textarea>`s are resizable — you'll notice the drag handle in the right-hand corner, which can be used to alter the size of the element on the page. This is controlled by the {{ cssxref("resize") }} CSS property — resizing is enabled by default, but you can explicitly disable it using a `resize` value of `none`: ```css textarea { resize: none; } ``` ### Styling valid and invalid values Valid and invalid values of a `<textarea>` element (e.g. those within, and outside the bounds set by `minlength`, `maxlength`, or `required`) can be highlighted using the {{cssxref(":valid")}} and {{cssxref(":invalid")}} pseudo-classes. For example, to give your textarea a different border depending on whether it is valid or invalid: ```css textarea:invalid { border: 2px dashed red; } textarea:valid { border: 2px solid lime; } ``` ## Examples ### Basic example The following example shows a very simple textarea, with a set numbers of rows and columns and some default content. ```html <textarea name="textarea" rows="10" cols="50">Write something here</textarea> ``` #### Result {{ EmbedLiveSample('Basic_example','600','150') }} ### Example using "minlength" and "maxlength" This example has a minimum and maximum number of characters — of 10 and 20 respectively. Try it and see. ```html <textarea name="textarea" rows="5" cols="30" minlength="10" maxlength="20"> Write something here… </textarea> ``` #### Result {{ EmbedLiveSample('Example using "minlength" and "maxlength"','600','80') }} Note that `minlength` doesn't stop the user from removing characters so that the number entered goes past the minimum, but it does make the value entered into the `<textarea>` invalid. Also note that even if you have a `minlength` value set (3, for example), an empty `<textarea>` is still considered valid unless you also have the `required` attribute set. ### Example using "placeholder" This example has a placeholder set. Notice how it disappears when you start typing into the box. ```html <textarea name="textarea" rows="5" cols="30" placeholder="Comment text."></textarea> ``` #### Result {{ EmbedLiveSample('Example using "placeholder"','600','100') }} > **Note:** Placeholders should only be used to show an example of the type of data that should be entered into a form; they are _not_ a substitute for a proper {{HTMLElement("label")}} element tied to the input. See [`<input>` labels](/en-US/docs/Web/HTML/Element/input#labels) for a full explanation. ### Disabled and readonly This example shows two `<textarea>`s — one of which is `disabled`, and one of which is `readonly`. Have a play with both and you'll see the difference in behavior — the `disabled` element is not selectable in any way (and its value is not submitted), whereas the `readonly` element is selectable and its contents copyable (and its value is submitted); you just can't edit the contents. > **Note:** In browsers other than Firefox, such as chrome, the `disabled` textarea content may be selectable and copyable. ```html <textarea name="textarea" rows="5" cols="30" disabled> I am a disabled textarea. </textarea> <textarea name="textarea" rows="5" cols="30" readonly> I am a read-only textarea. </textarea> ``` #### Result {{ EmbedLiveSample('Disabled_and_readonly','600','100') }} ## 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#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_labelable" >labelable</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form_resettable" >resettable</a >, and <a href="/en-US/docs/Web/HTML/Content_categories#form_submittable" >submittable</a > <a href="/en-US/docs/Web/HTML/Content_categories#form-associated_" >form-associated</a > element. </td> </tr> <tr> <th scope="row">Permitted content</th> <td>Text</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/textbox_role" >textbox</a ></code > </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("HTMLTextAreaElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also Other form-related elements: - {{ HTMLElement("form") }} - {{ HTMLElement("button") }} - {{ HTMLElement("datalist") }} - {{ HTMLElement("legend") }} - {{ HTMLElement("label") }} - {{ HTMLElement("select") }} - {{ HTMLElement("optgroup") }} - {{ HTMLElement("option") }} - {{ HTMLElement("input") }} - {{ HTMLElement("fieldset") }} - {{ HTMLElement("output") }} - {{ HTMLElement("progress") }} - {{ HTMLElement("meter") }}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/strong/index.md
--- title: "<strong>: The Strong Importance element" slug: Web/HTML/Element/strong page-type: html-element browser-compat: html.elements.strong --- {{HTMLSidebar}} The **`<strong>`** [HTML](/en-US/docs/Web/HTML) element indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type. {{EmbedInteractiveExample("pages/tabbed/strong.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<strong>` element is for content that is of "strong importance," including things of great seriousness or urgency (such as warnings). This could be a sentence that is of great importance to the whole page, or you could merely try to point out that some words are of greater importance compared to nearby content. Typically this element is rendered by default using a bold font weight. However, it should _not_ be used to apply bold styling; use the CSS {{cssxref("font-weight")}} property for that purpose. Use the {{HTMLElement("b")}} element to draw attention to certain text without indicating a higher level of importance. Use the {{HTMLElement("em")}} element to mark text that has stress emphasis. Another accepted use for `<strong>` is to denote the labels of paragraphs which represent notes or warnings within the text of a page. ### \<b> vs. \<strong> It is often confusing to new developers why there are so many ways to express the same thing on a rendered website. {{HTMLElement("b")}} and `<strong>` are perhaps one of the most common sources of confusion, causing developers to ask "Should I use `<b>` or `<strong>`? Don't they both do the same thing?" Not exactly. The `<strong>` element is for content that is of greater importance, while the `<b>` element is used to draw attention to text without indicating that it's more important. It may help to realize that both are valid and semantic elements in HTML and that it's a coincidence that they both have the same default styling (boldface) in most browsers (although some older browsers actually underline `<strong>`). Each element is meant to be used in certain types of scenarios, and if you want to bold text for decoration, you should instead actually use the CSS {{cssxref("font-weight")}} property. The intended meaning or purpose of the enclosed text should be what determines which element you use. Communicating meaning is what semantics are all about. ### \<em> vs. \<strong> Adding to the confusion is the fact that while HTML 4 defined `<strong>` as indicating a stronger emphasis, HTML 5 defines `<strong>` as representing "strong importance for its contents." This is an important distinction to make. While `<em>` is used to change the meaning of a sentence as spoken emphasis does ("I _love_ carrots" vs. "I love _carrots_"), `<strong>` is used to give portions of a sentence added importance (e.g., "**Warning!** This is **very dangerous.**") Both `<strong>` and `<em>` can be nested to increase the relative degree of importance or stress emphasis, respectively. ## Examples ### Basic example ```html <p> Before proceeding, <strong>make sure you put on your safety goggles</strong>. </p> ``` #### Result {{EmbedLiveSample("Basic_example", 650, 80)}} ### Labeling warnings ```html <p> <strong>Important:</strong> Before proceeding, make sure you add plenty of butter. </p> ``` #### Result {{EmbedLiveSample("Labeling_warnings", 650, 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>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/structural_roles#structural_roles_with_html_equivalents">strong</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("b")}} element - The {{HTMLElement("em")}} element - The {{cssxref("font-weight")}} property
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/header/index.md
--- title: "<header>: The Header element" slug: Web/HTML/Element/header page-type: html-element browser-compat: html.elements.header --- {{HTMLSidebar}} The **`<header>`** [HTML](/en-US/docs/Web/HTML) element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also a logo, a search form, an author name, and other elements. {{EmbedInteractiveExample("pages/tabbed/header.html", "tabbed-standard")}} ## Usage notes The `<header>` element has an identical meaning to the site-wide [`banner`](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) landmark role, unless nested within sectioning content. Then, the `<header>` element is not a landmark. The `<header>` element can define a global site header, described as a `banner` in the accessibility tree. It usually includes a logo, company name, search feature, and possibly the global navigation or a slogan. It is generally located at the top of the page. Otherwise, it is a `section` in the accessibility tree, and usually contains the surrounding section's heading (an `h1` – `h6` element) and optional subheading, but this is **not** required. ### Historical Usage The `<header>` element originally existed at the very beginning of HTML for headings. It is seen in [the very first website](http://info.cern.ch/). At some point, headings became [`<h1>` through `<h6>`](/en-US/docs/Web/HTML/Element/Heading_Elements), allowing `<header>` to be free to fill a different role. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ### Page Header ```html <header> <h1>Main Page Title</h1> <img src="mdn-logo-sm.png" alt="MDN logo" /> </header> ``` #### Result {{EmbedLiveSample('Page Header')}} ### Article Header ```html <article> <header> <h2>The Planet Earth</h2> <p> Posted on Wednesday, <time datetime="2017-10-04">4 October 2017</time> by Jane Smith </p> </header> <p> We live on a planet that's blue and green, with so many things still unseen. </p> <p><a href="https://example.com/the-planet-earth/">Continue reading…</a></p> </article> ``` #### Result {{EmbedLiveSample('Article Header')}} ## Accessibility concerns The `<header>` element defines a [`banner`](/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role) landmark when its context is the {{HTMLElement('body')}} element. The HTML header element is not considered a banner landmark when it is descendant of an {{HTMLElement('article')}}, {{HTMLElement('aside')}}, {{HTMLElement('main')}}, {{HTMLElement('nav')}}, or {{HTMLElement('section')}} element. ## 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#palpable_content" >palpable content</a >. </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 <code>&#x3C;header></code> or {{HTMLElement("footer")}} descendant. </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#flow_content" >flow content</a >. Note that a <code>&#x3C;header></code> element must not be a descendant of an {{HTMLElement("address")}}, {{HTMLElement("footer")}} or another {{HTMLElement("header")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Banner_role">banner</a >, or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Generic_role" >generic</a > if a descendant of an <code><a href="/en-US/docs/Web/HTML/Element/article">article</a></code >, <code><a href="/en-US/docs/Web/HTML/Element/aside">aside</a></code >, <code><a href="/en-US/docs/Web/HTML/Element/main">main</a></code >, <code><a href="/en-US/docs/Web/HTML/Element/nav">nav</a></code> or <code><a href="/en-US/docs/Web/HTML/Element/section">section</a></code> element, or an element with <code >role=<a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Article_Role" >article</a ></code >, <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Complementary_role" >complementary</a ></code >, <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Main_role" >main</a ></code >, <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Navigation_Role" >navigation</a ></code > or <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Region_role" >region</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other section-related elements: {{HTMLElement("body")}}, {{HTMLElement("nav")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}, {{HTMLElement("footer")}}, {{HTMLElement("section")}}, {{HTMLElement("address")}}.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/noframes/index.md
--- title: "<noframes>: The Frame Fallback element" slug: Web/HTML/Element/noframes page-type: html-element status: - deprecated browser-compat: html.elements.noframes --- {{HTMLSidebar}}{{deprecated_header}} The **`<noframes>`** [HTML](/en-US/docs/Web/HTML) element provides content to be presented in browsers that don't support (or have disabled support for) the {{HTMLElement("frame")}} element. Although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. A `<noframes>` element can contain any HTML elements that are allowed within the body of an HTML document, except for the {{HTMLElement("frameset")}} and {{HTMLElement("frame")}} elements, since using frames when they aren't supported doesn't make sense. `<noframes>` can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers the same or similar functionality. > **Note:** This element is obsolete and shouldn't be used, since the {{HTMLElement("frame")}} and {{HTMLElement("frameset")}} elements are also obsolete. When frames are needed at all, they should be presented using the {{HTMLElement("iframe")}} element. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). It has no other attributes available. ## Example In this example, we see a frameset with two frames. In addition, `<noframes>` is used to present an explanatory message if the {{Glossary("user agent")}} doesn't support frames. ```html <!doctype html> <html lang="en-US"> <head> <!-- Document metadata goes here --> </head> <frameset rows="45%, 55%"> <frame src="https://developer.mozilla.org/en/HTML/Element/frameset" /> <frame src="https://developer.mozilla.org/en/HTML/Element/frame" /> <noframes> <p> It seems your browser does not support frames or is configured to not allow them. </p> </noframes> </frameset> </html> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("frameset")}} - {{HTMLElement("frame")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/output/index.md
--- title: "<output>: The Output element" slug: Web/HTML/Element/output page-type: html-element browser-compat: html.elements.output --- {{HTMLSidebar}} The **`<output>`** [HTML](/en-US/docs/Web/HTML) element is a container element into which a site or app can inject the results of a calculation or the outcome of a user action. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `for` - : A space-separated list of other elements' [`id`](/en-US/docs/Web/HTML/Global_attributes#id)s, indicating that those elements contributed input values to (or otherwise affected) the calculation. - `form` - : The {{HTMLElement("form")}} element to associate the output with (its _form owner_). The value of this attribute must be the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of a `<form>` in the same document. (If this attribute is not set, the `<output>` is associated with its ancestor `<form>` element, if any.) This attribute lets you associate `<output>` elements to `<form>`s anywhere in the document, not just inside a `<form>`. It can also override an ancestor `<form>` element. - `name` - : The element's name. Used in the {{domxref("HTMLFormElement.elements", "form.elements")}} API. The `<output>` value, name, and contents are NOT submitted during form submission. ## Examples In the following example, the form provides a slider whose value can range between `0` and `100`, and an {{HTMLElement("input")}} element into which you can enter a second number. The two numbers are added together, and the result is displayed in the `<output>` element each time the value of any of the controls changes. ```html <form oninput="result.value=parseInt(a.value)+parseInt(b.value)"> <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> </form> ``` ### Result {{ EmbedLiveSample('Examples')}} ## Accessibility concerns Many browsers implement this element as an [`aria-live`](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) region. Assistive technology will thereby announce the results of UI interactions posted inside it without requiring that focus is switched away from the controls that produce those results. ## 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#form_listed" >listed</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form_labelable" >labelable</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form_resettable" >resettable</a > <a href="/en-US/docs/Web/HTML/Content_categories#form-associated_content" >form-associated element</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="/en-US/docs/Web/Accessibility/ARIA/Roles/status_role"><code>status</code></a></td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLOutputElement")}}</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/head/index.md
--- title: "<head>: The Document Metadata (Header) element" slug: Web/HTML/Element/head page-type: html-element browser-compat: html.elements.head --- {{HTMLSidebar}} The **`<head>`** [HTML](/en-US/docs/Web/HTML) element contains machine-readable information ({{glossary("metadata")}}) about the document, like its [title](/en-US/docs/Web/HTML/Element/title), [scripts](/en-US/docs/Web/HTML/Element/script), and [style sheets](/en-US/docs/Web/HTML/Element/style). > **Note:** `<head>` primarily holds information for machine processing, not human-readability. For human-visible information, like top-level headings and listed authors, see the {{HTMLElement("header")}} element. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `profile` {{deprecated_inline}} - : The {{glossary("URI")}}s of one or more metadata profiles, separated by {{Glossary("whitespace", "white space")}}. ## Examples ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>Document title</title> </head> </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>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <p> If the document is an {{HTMLElement("iframe")}} <a href="/en-US/docs/Web/HTML/Element/iframe#srcdoc"><code>srcdoc</code></a> document, or if title information is available from a higher level protocol (like the subject line in HTML email), zero or more elements of metadata content. </p> <p> Otherwise, one or more elements of metadata content where exactly one is a {{HTMLElement("title")}} element. </p> </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag may be omitted if the first thing inside the <code>&#x3C;head></code> element is an element.<br />The end tag may be omitted if the first thing following the <code>&#x3C;head></code> element is not a space character or a comment. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td>An {{HTMLElement("html")}} element, as its first child.</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("HTMLHeadElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Elements that can be used inside the `<head>`: - {{HTMLElement("title")}} - {{HTMLElement("base")}} - {{HTMLElement("link")}} - {{HTMLElement("style")}} - {{HTMLElement("meta")}} - {{HTMLElement("script")}} - {{HTMLElement("noscript")}} - {{HTMLElement("template")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/ol/index.md
--- title: "<ol>: The Ordered List element" slug: Web/HTML/Element/ol page-type: html-element browser-compat: html.elements.ol --- {{HTMLSidebar}} The **`<ol>`** [HTML](/en-US/docs/Web/HTML) element represents an ordered list of items — typically rendered as a numbered list. {{EmbedInteractiveExample("pages/tabbed/ol.html", "tabbed-shorter")}} ## Attributes This element also accepts the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `reversed` - : This Boolean attribute specifies that the list's items are in reverse order. Items will be numbered from high to low. - `start` - : An integer to start counting from for the list items. Always an Arabic numeral (1, 2, 3, etc.), even when the numbering `type` is letters or Roman numerals. For example, to start numbering elements from the letter "d" or the Roman numeral "iv," use `start="4"`. - `type` - : Sets the numbering type: - `a` for lowercase letters - `A` for uppercase letters - `i` for lowercase Roman numerals - `I` for uppercase Roman numerals - `1` for numbers (default) The specified type is used for the entire list unless a different [`type`](/en-US/docs/Web/HTML/Element/li#type) attribute is used on an enclosed {{HTMLElement("li")}} element. > **Note:** Unless the type of the list number matters (like legal or technical documents where items are referenced by their number/letter), use the CSS {{CSSxRef("list-style-type")}} property instead. ## Usage notes Typically, ordered list items display with a preceding [marker](/en-US/docs/Web/CSS/::marker), such as a number or letter. The `<ol>` and {{HTMLElement("ul")}} elements may nest as deeply as desired, alternating between `<ol>` and `<ul>` however you like. The `<ol>` and {{HTMLElement("ul")}} elements both represent a list of items. The difference is with the `<ol>` element, the order is meaningful. For example: - Steps in a recipe - Turn-by-turn directions - The list of ingredients in decreasing proportion on nutrition information labels To determine which list to use, try changing the order of the list items; if the meaning changes, use the `<ol>` element — otherwise you can use {{HTMLElement("ul")}}. ## Examples ### Simple example ```html <ol> <li>Fee</li> <li>Fi</li> <li>Fo</li> <li>Fum</li> </ol> ``` #### Result {{EmbedLiveSample("Simple_example", 400, 100)}} ### Using Roman Numeral type ```html <ol type="i"> <li>Introduction</li> <li>List of Grievances</li> <li>Conclusion</li> </ol> ``` #### Result {{EmbedLiveSample("Using_Roman_Numeral_type", 400, 100)}} ### Using the start attribute ```html <p>Finishing places of contestants not in the winners' circle:</p> <ol start="4"> <li>Speedwalk Stu</li> <li>Saunterin' Sam</li> <li>Slowpoke Rodriguez</li> </ol> ``` #### Result {{EmbedLiveSample("Using_the_start_attribute", 400, 100)}} ### Nesting lists ```html <ol> <li>first item</li> <li> second item <!-- closing </li> tag is not here! --> <ol> <li>second item first subitem</li> <li>second item second subitem</li> <li>second item third subitem</li> </ol> </li> <!-- Here's the closing </li> tag --> <li>third item</li> </ol> ``` #### Result {{EmbedLiveSample("Nesting_lists", 400, 150)}} ### Unordered list inside ordered list ```html <ol> <li>first item</li> <li> second item <!-- closing </li> tag is not here! --> <ul> <li>second item first subitem</li> <li>second item second subitem</li> <li>second item third subitem</li> </ul> </li> <!-- Here's the closing </li> tag --> <li>third item</li> </ol> ``` #### Result {{EmbedLiveSample("Unordered_list_inside_ordered_list", 400, 150)}} ## 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 >, and if the <code>&#x3C;ol></code> element's children include at least one {{HTMLElement("li")}} element, <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content" >palpable content</a >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Zero or more {{ HTMLElement("li") }}, {{HTMLElement("script")}} and {{HTMLElement("template")}} elements. </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#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/List_role" >list</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/directory_role"><code>directory</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role"><code>listbox</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role"><code>menu</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role"><code>menubar</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role"><code>radiogroup</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role"><code>tablist</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/toolbar_role"><code>toolbar</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role"><code>tree</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLOListElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other list-related HTML Elements: {{HTMLElement("ul")}}, {{HTMLElement("li")}}, {{HTMLElement("menu")}} - CSS properties that may be specially useful to style the `<ol>` element: - the {{CSSxRef("list-style")}} property, to choose the way the ordinal displays - [CSS counters](/en-US/docs/Web/CSS/CSS_counter_styles/Using_CSS_counters), to handle complex nested lists - the {{CSSxRef("line-height")}} property, to simulate the deprecated `compact` attribute - the {{CSSxRef("margin")}} property, to control the list indentation
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/portal/index.md
--- title: "<portal>: The Portal element" slug: Web/HTML/Element/portal page-type: html-element status: - experimental browser-compat: html.elements.portal --- {{HTMLSidebar}}{{SeeCompatTable}} The **`<portal>`** [HTML](/en-US/docs/Web/HTML) element enables the embedding of another HTML page into the current one for the purposes of allowing smoother navigation into new pages. A `<portal>` is similar to an `<iframe>`. An `<iframe>` allows a separate {{Glossary("browsing context")}} to be embedded. However, the embedded content of a `<portal>` is more limited than that of an `<iframe>`. It cannot be interacted with, and therefore is not suitable for embedding widgets into a document. Instead, the `<portal>` acts as a preview of the content of another page. It can be navigated into therefore allowing for seamless transition to the embedded content. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `referrerpolicy` - : Sets the [referrer policy](/en-US/docs/Web/HTTP/Headers/Referrer-Policy) to use when requesting the page at the URL given as the value of the `src` attribute. - `src` - : The URL of the page to embed. ## Examples ### Basic example The following example will embed the contents of `https://example.com` as a preview. ```html <portal id="exampleportal" src="https://example.com/"></portal> ``` ## Accessibility concerns The preview displayed by a `<portal>` is not interactive, therefore does not receive input events or focus. Therefore the embedded contents of the portal are not exposed as elements in the {{Glossary("accessibility tree")}}. The portal can be navigated to and activated like a button, the default behavior when clicking on the portal is to activate it. Portals are given a default label which is the title of the embedded page. If no title is present the visible text in the preview is concatenated to create a label. The [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute can be used to override this. Portals used for prerendering only should be hidden with the hidden HTML attribute or the CSS {{cssxref("display")}} property with a value of `none`. When using animations during portal activation the {{cssxref("@media/prefers-reduced-motion", "prefers-reduced-motion")}} [media feature](/en-US/docs/Web/CSS/@media#media_features) should be respected. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role" >button</a > </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLPortalElement")}}</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/select/index.md
--- title: "<select>: The HTML Select element" slug: Web/HTML/Element/select page-type: html-element browser-compat: html.elements.select --- {{HTMLSidebar}} The **`<select>`** [HTML](/en-US/docs/Web/HTML) element represents a control that provides a menu of options. {{EmbedInteractiveExample("pages/tabbed/select.html", "tabbed-standard")}} The above example shows typical `<select>` usage. It is given an `id` attribute to enable it to be associated with a {{htmlelement("label")}} for accessibility purposes, as well as a `name` attribute to represent the name of the associated data point submitted to the server. Each menu option is defined by an {{htmlelement("option")}} element nested inside the `<select>`. Each `<option>` element should have a [`value`](/en-US/docs/Web/HTML/Element/option#value) attribute containing the data value to submit to the server when that option is selected. If no `value` attribute is included, the value defaults to the text contained inside the element. You can include a [`selected`](/en-US/docs/Web/HTML/Element/option#selected) attribute on an `<option>` element to make it selected by default when the page first loads. The `<select>` element has some unique attributes you can use to control it, such as `multiple` to specify whether multiple options can be selected, and `size` to specify how many options should be shown at once. It also accepts most of the general form input attributes such as `required`, `disabled`, `autofocus`, etc. You can further nest {{HTMLElement("option")}} elements inside {{HTMLElement("optgroup")}} elements to create separate groups of options inside the dropdown. You can also include {{HTMLElement("hr")}} elements to create separators that add visual breaks between options. For further examples, see [The native form widgets: Drop-down content](/en-US/docs/Learn/Forms/Other_form_controls#drop-down_controls). ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `autocomplete` - : A string providing a hint for a {{Glossary("user agent", "user agent's")}} autocomplete feature. See [The HTML autocomplete attribute](/en-US/docs/Web/HTML/Attributes/autocomplete) for a complete list of values and details on how to use autocomplete. - `autofocus` - : This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form element in a document can have the `autofocus` attribute. - `disabled` - : This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example {{htmlelement("fieldset")}}; if there is no containing element with the `disabled` attribute set, then the control is enabled. - `form` - : The {{HTMLElement("form")}} element to associate the `<select>` with (its _form owner_). The value of this attribute must be the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of a `<form>` in the same document. (If this attribute is not set, the `<select>` is associated with its ancestor `<form>` element, if any.) This attribute lets you associate `<select>` elements to `<form>`s anywhere in the document, not just inside a `<form>`. It can also override an ancestor `<form>` element. - `multiple` - : This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When `multiple` is specified, most browsers will show a scrolling list box instead of a single line dropdown. - `name` - : This attribute is used to specify the name of the control. - `required` - : A Boolean attribute indicating that an option with a non-empty string value must be selected. - `size` - : If the control is presented as a scrolling list box (e.g. when `multiple` is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is `0`. > **Note:** According to the HTML specification, the default value for size should be `1`; however, in practice, this has been found to break some websites, and no other browser currently does that, so Mozilla has opted to continue to return `0` for the time being with Firefox. ## Usage notes ### Selecting multiple options On a desktop computer, there are a number of ways to select multiple options in a `<select>` element with a `multiple` attribute: Mouse users can hold the <kbd>Ctrl</kbd>, <kbd>Command</kbd>, or <kbd>Shift</kbd> keys (depending on what makes sense for your operating system) and then click multiple options to select/deselect them. > **Warning:** The mechanism for selecting multiple non-contiguous items via the keyboard described below currently only seems to work in Firefox. > > On macOS, the <kbd>Ctrl</kbd> + <kbd>Up</kbd> and <kbd>Ctrl</kbd> + <kbd>Down</kbd> shortcuts conflict with the OS default shortcuts for _Mission Control_ and _Application windows_, so you'll have to turn these off before it will work. Keyboard users can select multiple contiguous items by: - Focusing on the `<select>` element (e.g. using <kbd>Tab</kbd> ). - 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. - Holding down the <kbd>Shift</kbd> key and then using the <kbd>Up</kbd> and <kbd>Down</kbd> cursor keys to increase or decrease the range of items selected. Keyboard users can select multiple non-contiguous items by: - Focusing on the `<select>` element (e.g. using <kbd>Tab</kbd> ). - Holding down the <kbd>Ctrl</kbd> key then using the <kbd>Up</kbd> and <kbd>Down</kbd> cursor keys to change the "focused" select option, i.e. the one that will be selected if you choose to do so. The "focused" select option is highlighted with a dotted outline, in the same way as a keyboard-focused link. - Pressing <kbd>Space</kbd> to select/deselect "focused" select options. ## Styling with CSS The `<select>` element is notoriously difficult to style productively with CSS. You can affect certain aspects like any element — for example, manipulating the [box model](/en-US/docs/Learn/CSS/Building_blocks/The_box_model), the [displayed font](/en-US/docs/Web/CSS/CSS_fonts), etc., and you can use the {{cssxref("appearance")}} property to remove the default system `appearance`. However, these properties don't produce a consistent result across browsers, and it is hard to do things like line different types of form element up with one another in a column. The `<select>` element's internal structure is complex, and hard to control. If you want to get full control, you should consider using a library with good facilities for styling form widgets, or try rolling your own dropdown menu using non-semantic elements, JavaScript, and [WAI-ARIA](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics) to provide semantics. For more useful information on styling `<select>`, see: - [Styling HTML forms](/en-US/docs/Learn/Forms/Styling_web_forms) - [Advanced styling for HTML forms](/en-US/docs/Learn/Forms/Advanced_form_styling) Also see the "Customizing select styles" example below for an example of you could attempt a simple `<select>` styling. ## Examples ### Basic select The following example creates a very simple dropdown menu, the second option of which is selected by default. ```html <!-- The second value will be selected initially --> <select name="choice"> <option value="first">First Value</option> <option value="second" selected>Second Value</option> <option value="third">Third Value</option> </select> ``` #### Result {{EmbedLiveSample("Basic_select", "", "100")}} ### Select with grouping options The following example creates a dropdown menu with grouping using {{HTMLElement("optgroup")}} and {{HTMLElement("hr")}} to make it easier for the user to understand the content in the dropdown. ```html <label for="hr-select">Your favorite food</label> <br /> <select name="foods" id="hr-select"> <option value="">Choose a food</option> <hr /> <optgroup label="Fruit"> <option value="apple">Apples</option> <option value="banana">Bananas</option> <option value="cherry">Cherries</option> <option value="damson">Damsons</option> </optgroup> <hr /> <optgroup label="Vegetables"> <option value="artichoke">Artichokes</option> <option value="broccoli">Broccoli</option> <option value="cabbage">Cabbages</option> </optgroup> <hr /> <optgroup label="Meat"> <option value="beef">Beef</option> <option value="chicken">Chicken</option> <option value="pork">Pork</option> </optgroup> <hr /> <optgroup label="Fish"> <option value="cod">Cod</option> <option value="haddock">Haddock</option> <option value="salmon">Salmon</option> <option value="turbot">Turbot</option> </optgroup> </select> ``` #### Result {{EmbedLiveSample("select_with_grouping_options", "", "100")}} ### Advanced select with multiple features The follow example is more complex, showing off more features you can use on a `<select>` element: ```html <label> Please choose one or more pets: <select name="pets" multiple size="4"> <optgroup label="4-legged pets"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster" disabled>Hamster</option> </optgroup> <optgroup label="Flying pets"> <option value="parrot">Parrot</option> <option value="macaw">Macaw</option> <option value="albatross">Albatross</option> </optgroup> </select> </label> ``` #### Result {{EmbedLiveSample("Advanced_select_with_multiple_features", "", "100")}} You'll see that: - Multiple options are selectable because we've included the `multiple` attribute. - The `size` attribute causes only 4 lines to display at a time; you can scroll to view all the options. - We've included {{htmlelement("optgroup")}} elements to divide the options up into different groups. This is a purely visual grouping, its visualization generally consists of the group name being bolded, and the options being indented. - The "Hamster" option includes a `disabled` attribute and therefore can't be selected at all. ### Customizing select styles This example shows how you could use some CSS and JavaScript to provide extensive custom styling for a `<select>` box. This example basically: - Clones the `<select>`'s context (the [`<option>`](/en-US/docs/Web/HTML/Element/option) elements) in a parent wrapper and reimplements the standard expected behavior using additional HTML elements and JavaScript. This includes basic tab behavior to provide keyboard accessibility. - Maps some standards native `attributes` to `data-attributes` of the new elements in order to manage state and CSS. > **Note:** Not all native features are supported, it's a Proof of Concept. IT starts from standard HTML but the same results can be achieved starting from JSON data, custom HTML, or other solutions. #### HTML ```html <form> <fieldset> <legend>Standard controls</legend> <select name="1A" id="select" autocomplete="off" required> <option>Carrots</option> <option>Peas</option> <option>Beans</option> <option>Pneumonoultramicroscopicsilicovolcanoconiosis</option> </select> </fieldset> <fieldset id="custom"> <legend>Custom controls</legend> <select name="2A" id="select" autocomplete="off" required> <option>Carrots</option> <option>Peas</option> <option>Beans</option> <option>Pneumonoultramicroscopicsilicovolcanoconiosis</option> </select> </fieldset> </form> ``` #### CSS ```css body { font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif; } .select:focus { border-color: blue; } html body form fieldset#custom div.select[data-multiple] div.header { display: none; } html body form fieldset#custom div.select div.header { content: "↓"; display: flex; flex: 1; align-items: center; padding: 0; position: relative; width: auto; box-sizing: border-box; border-width: 1px; border-style: inherit; border-color: inherit; border-radius: inherit; } html body form fieldset#custom div.select div.header::after { content: "↓"; align-self: stretch; display: flex; align-content: center; justify-content: center; justify-items: center; align-items: center; padding: 0.5em; } html body form fieldset#custom div.select div.header:hover::after { background-color: blue; } .select .header select { appearance: none; font-family: inherit; font-size: inherit; padding: 0; border-width: 0; width: 100%; flex: 1; display: none; } .select .header select optgroup { display: none; } .select select div.option { display: none; } html body form fieldset#custom div.select { user-select: none; box-sizing: border-box; position: relative; border-radius: 4px; border-style: solid; border-width: 0; border-color: gray; width: auto; display: inline-block; } html body form fieldset#custom div.select:focus, html body form fieldset#custom div.select:hover { border-color: blue; } html body form fieldset#custom div.select[data-open] { border-bottom-left-radius: 0; border-bottom-right-radius: 0; } html body form fieldset#custom div.select[data-open] datalist { display: initial; } html body form fieldset#custom div.select datalist { appearance: none; position: absolute; border-style: solid; border-width: 1px; border-color: gray; left: 0; display: none; width: 100%; box-sizing: border-box; z-index: 2; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } html body form fieldset#custom div.select datalist div.option { background-color: white; margin-bottom: 1px; cursor: pointer; padding: 0.5em; border-width: 0; } html body form fieldset#custom div.select datalist div.option:hover, html body form fieldset#custom div.select datalist div.option:focus, html body form fieldset#custom div.select datalist div.option:checked { background-color: blue; color: white; } html body form fieldset#custom div.select div.optgroup div.option[data-disabled] { color: gray; } html body form fieldset#custom div.select div.optgroup div.option[data-checked] { background-color: blue; color: white; } html body form fieldset#custom div.select div.optgroup div.label { font-weight: bold; } html body form fieldset#custom div.select div.optgroup div.option div.label { font-weight: normal; padding: 0.25em; } html body form fieldset#custom div.select div.header span { flex: 1; padding: 0.5em; } ``` #### JavaScript ```js const selects = custom.querySelectorAll("select"); for (const select of selects) { const div = document.createElement("div"); const header = document.createElement("div"); const datalist = document.createElement("datalist"); const optgroups = select.querySelectorAll("optgroup"); const span = document.createElement("span"); const options = select.options; const parent = select.parentElement; const multiple = select.hasAttribute("multiple"); function onclick(e) { const disabled = this.hasAttribute("data-disabled"); select.value = this.dataset.value; span.innerText = this.dataset.label; if (disabled) return; if (multiple) { if (e.shiftKey) { const checked = this.hasAttribute("data-checked"); if (checked) { this.removeAttribute("data-checked"); } else { this.setAttribute("data-checked", ""); } } else { const options = div.querySelectorAll(".option"); for (let i = 0; i < options.length; i++) { const option = options[i]; option.removeAttribute("data-checked"); } this.setAttribute("data-checked", ""); } } } function onkeyup(e) { e.preventDefault(); e.stopPropagation(); if (e.keyCode === 13) { this.click(); } } div.classList.add("select"); header.classList.add("header"); div.tabIndex = 1; select.tabIndex = -1; span.innerText = select.label; header.appendChild(span); for (const attribute of select.attributes) { div.dataset[attribute.name] = attribute.value; } for (let i = 0; i < options.length; i++) { const option = document.createElement("div"); const label = document.createElement("div"); const o = options[i]; for (const attribute of o.attributes) { option.dataset[attribute.name] = attribute.value; } option.classList.add("option"); label.classList.add("label"); label.innerText = o.label; option.dataset.value = o.value; option.dataset.label = o.label; option.onclick = onclick; option.onkeyup = onkeyup; option.tabIndex = i + 1; option.appendChild(label); datalist.appendChild(option); } div.appendChild(header); for (const o of optgroups) { const optgroup = document.createElement("div"); const label = document.createElement("div"); const options = o.querySelectorAll("option"); Object.assign(optgroup, o); optgroup.classList.add("optgroup"); label.classList.add("label"); label.innerText = o.label; optgroup.appendChild(label); div.appendChild(optgroup); for (const o of options) { const option = document.createElement("div"); const label = document.createElement("div"); for (const attribute of o.attributes) { option.dataset[attribute.name] = attribute.value; } option.classList.add("option"); label.classList.add("label"); label.innerText = o.label; option.tabIndex = i + 1; option.dataset.value = o.value; option.dataset.label = o.label; option.onclick = onclick; option.onkeyup = onkeyup; option.tabIndex = i + 1; option.appendChild(label); optgroup.appendChild(option); } } div.onclick = (e) => { e.preventDefault(); }; parent.insertBefore(div, select); header.appendChild(select); div.appendChild(datalist); datalist.style.top = `${header.offsetTop + header.offsetHeight}px`; div.onclick = (e) => { if (!multiple) { const open = div.hasAttribute("data-open"); e.stopPropagation(); if (open) { div.removeAttribute("data-open"); } else { div.setAttribute("data-open", ""); } } }; div.onkeyup = (event) => { event.preventDefault(); if (event.keyCode === 13) { div.click(); } }; document.addEventListener("click", (e) => { if (div.hasAttribute("data-open")) { div.removeAttribute("data-open"); } }); const width = Math.max( ...Array.from(options).map((e) => { span.innerText = e.label; return div.offsetWidth; }), ); console.log(width); div.style.width = `${width}px`; } document.forms[0].onsubmit = (e) => { const data = new FormData(this); e.preventDefault(); submit.innerText = JSON.stringify([...data.entries()]); }; ``` #### Result {{EmbedGHLiveSample("html-examples/custom-select", '100%', 300)}} ## Accessibility concerns The `<hr>` within a `<select>` should be considered purely decorative, as they are currently not exposed within the accessibility tree and therefore not exposed to assistive technologies. ## 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#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_labelable" >labelable</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form_resettable" >resettable</a >, and <a href="/en-US/docs/Web/HTML/Content_categories#form_submittable" >submittable</a > <a href="/en-US/docs/Web/HTML/Content_categories#form-associated_" >form-associated </a >element </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Zero or more {{HTMLElement("option")}}, {{HTMLElement("optgroup")}} or {{HTMLElement("hr")}} elements. </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="/en-US/docs/Web/Accessibility/ARIA/Roles/combobox_role"><code>combobox</code></a> with <strong>no</strong> <code>multiple</code> attribute and <strong>no</strong> <code>size</code> attribute greater than 1, otherwise <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role"><code>listbox</code></a> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role"><code>menu</code></a> with <strong>no</strong> <code>multiple</code> attribute and <strong>no</strong> <code>size</code> attribute greater than 1, otherwise no <code>role</code> permitted </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLSelectElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Events fired by `<select>`: {{domxref("HTMLElement/change_event", "change")}}, {{domxref("Element/input_event", "input")}} - The {{HTMLElement("option")}} element - The {{HTMLElement("optgroup")}} element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/bdi/index.md
--- title: "<bdi>: The Bidirectional Isolate element" slug: Web/HTML/Element/bdi page-type: html-element browser-compat: html.elements.bdi --- {{HTMLSidebar}} The **`<bdi>`** [HTML](/en-US/docs/Web/HTML) element tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text. It's particularly useful when a website dynamically inserts some text and doesn't know the directionality of the text being inserted. {{EmbedInteractiveExample("pages/tabbed/bdi.html", "tabbed-standard")}} Bidirectional text is text that may contain both sequences of characters that are arranged left-to-right (LTR) and sequences of characters that are arranged right-to-left (RTL), such as an Arabic quotation embedded in an English string. Browsers implement the [Unicode Bidirectional Algorithm](https://www.w3.org/International/articles/inline-bidi-markup/uba-basics) to handle this. In this algorithm, characters are given an implicit directionality: for example, Latin characters are treated as LTR while Arabic characters are treated as RTL. Some other characters (such as spaces and some punctuation) are treated as neutral and are assigned directionality based on that of their surrounding characters. Usually, the bidirectional algorithm will do the right thing without the author having to provide any special markup but, occasionally, the algorithm needs help. That's where `<bdi>` comes in. The `<bdi>` element is used to wrap a span of text and instructs the bidirectional algorithm to treat this text in isolation from its surroundings. This works in two ways: - The directionality of text embedded in `<bdi>` _does not influence_ the directionality of the surrounding text. - The directionality of text embedded in `<bdi>` _is not influenced by_ the directionality of the surrounding text. For example, consider some text like: ```plain EMBEDDED-TEXT - 1st place ``` If `EMBEDDED-TEXT` is LTR, this works fine. But if `EMBEDDED-TEXT` is RTL, then `- 1` will be treated as RTL text (because it consists of neutral and weak characters). The result will be garbled: ```plain 1 - EMBEDDED-TEXTst place ``` If you know the directionality of `EMBEDDED-TEXT` in advance, you can fix this problem by wrapping `EMBEDDED-TEXT` in a {{HTMLElement("span")}} with the [`dir`](/en-US/docs/Web/HTML/Global_attributes#dir) attribute set to the known directionality. But if you don't know the directionality - for example, because `EMBEDDED-TEXT` is being read from a database or entered by the user - you should use `<bdi>` to prevent the directionality of `EMBEDDED-TEXT` from affecting its surroundings. Though the same visual effect can be achieved using the CSS rule {{cssxref("unicode-bidi")}}`: isolate` on a {{HTMLElement("span")}} or another text-formatting element, HTML authors should not use this approach because it is not semantic and browsers are allowed to ignore CSS styling. Embedding the characters in `<span dir="auto">` has the same effect as using `<bdi>`, but its semantics are less clear. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes), except that the [`dir`](/en-US/docs/Web/HTML/Global_attributes#dir) attribute behaves differently than normal: it defaults to `auto`, meaning its value is never inherited from the parent element. This means that unless you specify a value of either `rtl` or `ltr` for `dir`, the {{Glossary("user agent")}} will determine the correct directionality to use based on the contents of the `<bdi>`. ## Examples ### No bdi with only LTR This example lists the winners of a competition using {{HTMLElement("span")}} elements only. When the names only contain LTR text the results look fine: ```html <ul> <li><span class="name">Henrietta Boffin</span> - 1st place</li> <li><span class="name">Jerry Cruncher</span> - 2nd place</li> </ul> ``` ```css hidden body { border: 1px solid #3f87a6; max-width: calc(100% - 40px - 6px); padding: 20px; width: calc(100% - 40px - 6px); border-width: 1px 1px 1px 5px; } ``` {{ EmbedLiveSample('No_bdi_with_only_LTR','','120','','','bdi-example') }} ### No bdi with RTL text This example lists the winners of a competition using {{HTMLElement("span")}} elements only, and one of the winners has a name consisting of RTL text. In this case the "`- 1`", which consists of characters with neutral or weak directionality, will adopt the directionality of the RTL text, and the result will be garbled: ```html <ul> <li><span class="name">اَلأَعْشَى</span> - 1st place</li> <li><span class="name">Jerry Cruncher</span> - 2nd place</li> </ul> ``` ```css hidden body { border: 1px solid #3f87a6; max-width: calc(100% - 40px - 6px); padding: 20px; width: calc(100% - 40px - 6px); border-width: 1px 1px 1px 5px; } ``` {{ EmbedLiveSample('No_bdi_with_RTL_text','','120','','','bdi-example') }} ### Using bdi with LTR and RTL text This example lists the winners of a competition using `<bdi>` elements. These elements instruct the browser to treat the name in isolation from its embedding context, so the example output is properly ordered: ```html <ul> <li><bdi class="name">اَلأَعْشَى</bdi> - 1st place</li> <li><bdi class="name">Jerry Cruncher</bdi> - 2nd place</li> </ul> ``` ```css hidden body { border: 1px solid #3f87a6; max-width: calc(100% - 40px - 6px); padding: 20px; width: calc(100% - 40px - 6px); border-width: 1px 1px 1px 5px; } ``` {{ EmbedLiveSample('Using_bdi_with_LTR_and_RTL_text','','120','','','bdi-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("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Inline markup and bidirectional text in HTML](https://www.w3.org/International/articles/inline-bidi-markup/) - [Unicode Bidirectional Algorithm basics](https://www.w3.org/International/articles/inline-bidi-markup/uba-basics) - {{Glossary("Localization")}} - Related HTML element: {{HTMLElement("bdo")}} - Related CSS properties: {{cssxref("direction")}}, {{cssxref("unicode-bidi")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/dl/index.md
--- title: "<dl>: The Description List element" slug: Web/HTML/Element/dl page-type: html-element browser-compat: html.elements.dl --- {{HTMLSidebar}} The **`<dl>`** [HTML](/en-US/docs/Web/HTML) element represents a description list. The element encloses a list of groups of terms (specified using the {{HTMLElement("dt")}} element) and descriptions (provided by {{HTMLElement("dd")}} elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs). {{EmbedInteractiveExample("pages/tabbed/dl.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ### Single term and description ```html <dl> <dt>Firefox</dt> <dd> A free, open source, cross-platform, graphical web browser developed by the Mozilla Corporation and hundreds of volunteers. </dd> <!-- Other terms and descriptions --> </dl> ``` #### Result {{EmbedLiveSample("Single_term_and_description")}} ### Multiple terms, single description ```html <dl> <dt>Firefox</dt> <dt>Mozilla Firefox</dt> <dt>Fx</dt> <dd> A free, open source, cross-platform, graphical web browser developed by the Mozilla Corporation and hundreds of volunteers. </dd> <!-- Other terms and descriptions --> </dl> ``` #### Result {{EmbedLiveSample("Multiple_terms_single_description")}} ### Single term, multiple descriptions ```html <dl> <dt>Firefox</dt> <dd> A free, open source, cross-platform, graphical web browser developed by the Mozilla Corporation and hundreds of volunteers. </dd> <dd> The Red Panda also known as the Lesser Panda, Wah, Bear Cat or Firefox, is a mostly herbivorous mammal, slightly larger than a domestic cat (60 cm long). </dd> <!-- Other terms and descriptions --> </dl> ``` #### Result {{EmbedLiveSample("Single_term_multiple_descriptions")}} ### Multiple terms and descriptions It is also possible to define multiple terms with multiple corresponding descriptions, by combining the examples above. ### Metadata Description lists are useful for displaying metadata as a list of key-value pairs. ```html <dl> <dt>Name</dt> <dd>Godzilla</dd> <dt>Born</dt> <dd>1952</dd> <dt>Birthplace</dt> <dd>Japan</dd> <dt>Color</dt> <dd>Green</dd> </dl> ``` #### Result {{EmbedLiveSample('Metadata')}} Tip: It can be handy to define a key-value separator in the CSS, such as: ```css dt::after { content: ": "; } ``` ### Wrapping name-value groups in `div` elements [WHATWG](/en-US/docs/Glossary/WHATWG) HTML allows wrapping each name-value group in a {{HTMLElement("dl")}} element in a {{HTMLElement("div")}} element. This can be useful when using [microdata](/en-US/docs/Web/HTML/Microdata), or when [global attributes](/en-US/docs/Web/HTML/Global_attributes) apply to a whole group, or for styling purposes. ```html <dl> <div> <dt>Name</dt> <dd>Godzilla</dd> </div> <div> <dt>Born</dt> <dd>1952</dd> </div> <div> <dt>Birthplace</dt> <dd>Japan</dd> </div> <div> <dt>Color</dt> <dd>Green</dd> </div> </dl> ``` #### Result {{EmbedLiveSample('Wrapping name-value groups in `div` elements')}} ## Notes Do not use this element (nor {{HTMLElement("ul")}} elements) to merely create indentation on a page. Although it works, this is a bad practice and obscures the meaning of description lists. To change the indentation of a description term, use the [CSS](/en-US/docs/Web/CSS) {{cssxref("margin")}} property. ## Accessibility concerns Each screen reader exposes `<dl>` content differently, including total count, terms/definitions context, and navigation methods. These differences are not necessarily bugs. As of iOS 14, VoiceOver will announce that `<dl>` content is a list when navigating with the virtual cursor (not via the read-all command). VoiceOver does not support list navigation commands with `<dl>`. Be careful applying ARIA `term` and `definition` roles to `<dl>` constructs as VoiceOver (macOS and iOS) will adjust how they are announced. - [VoiceOver on iOS 14 Supports Description Lists](https://adrianroselli.com/2020/09/voiceover-on-ios-14-supports-description-lists.html) - [Brief Note on Description List Support](https://adrianroselli.com/2022/12/brief-note-on-description-list-support.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#flow_content" >Flow content</a >, and if the <code>&#x3C;dl></code> element's children include one name-value group, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <p> Either: Zero or more groups each consisting of one or more {{HTMLElement("dt")}} elements followed by one or more {{HTMLElement("dd")}} elements, optionally intermixed with {{HTMLElement("script")}} and {{HTMLElement("template")}} elements.<br />Or: (in {{Glossary("WHATWG")}} HTML, {{Glossary("W3C")}} HTML 5.2 and later) One or more {{HTMLElement("div")}} elements, optionally intermixed with {{HTMLElement("script")}} and {{HTMLElement("template")}} elements. </p> </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#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> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></a>, <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/List_role" >list</a ></code >, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLDListElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dt")}} - {{HTMLElement("dd")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/section/index.md
--- title: "<section>: The Generic Section element" slug: Web/HTML/Element/section page-type: html-element browser-compat: html.elements.section --- {{HTMLSidebar}} The **`<section>`** [HTML](/en-US/docs/Web/HTML) element represents a generic standalone section of a document, which doesn't have a more specific semantic element to represent it. Sections should always have a heading, with very few exceptions. {{EmbedInteractiveExample("pages/tabbed/section.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes As mentioned above, `<section>` is a generic sectioning element, and should only be used if there isn't a more specific element to represent it. As an example, a navigation menu should be wrapped in a {{htmlelement("nav")}} element, but a list of search results or a map display and its controls don't have specific elements, and could be put inside a `<section>`. Also consider these cases: - If the contents of the element represent a standalone, atomic unit of content that makes sense syndicated as a standalone piece (e.g. a blog post or blog comment, or a newspaper article), the {{HTMLElement("article")}} element would be a better choice. - If the contents represent useful tangential information that works alongside the main content, but is not directly part of it (like related links, or an author bio), use an {{HTMLElement("aside")}}. - If the contents represent the main content area of a document, use {{HTMLElement("main")}}. - If you are only using the element as a styling wrapper, use a {{HTMLElement("div")}} instead. To reiterate, each `<section>` should be identified, typically by including a heading ({{HTMLElement("Heading_Elements", "h1")}} - {{HTMLElement("Heading_Elements", "h6")}} element) as a child of the `<section>` element, wherever possible. See below for examples of where you might see a `<section>` without a heading. ## Examples ### Simple usage example #### Before ```html <div> <h2>Heading</h2> <p>Bunch of awesome content</p> </div> ``` ##### Result {{EmbedLiveSample('Before')}} #### After ```html <section> <h2>Heading</h2> <p>Bunch of awesome content</p> </section> ``` ##### Result {{EmbedLiveSample('After')}} ### Using a section without a heading Circumstances where you might see `<section>` used without a heading are typically found in web application/UI sections rather than in traditional document structures. In a document, it doesn't really make any sense to have a separate section of content without a heading to describe its contents. Such headings are useful for all readers, but particularly useful for users of assistive technologies like screen readers, and they are also good for SEO. Consider however a secondary navigation mechanism. If the global navigation is already wrapped in a `<nav>` element, you could conceivably wrap a previous/next menu in a `<section>`: ```html <section> <a href="#">Previous article</a> <a href="#">Next article</a> </section> ``` Or what about some kind of button bar for controlling your app? This might not necessarily want a heading, but it is still a distinct section of the document: ```html <section> <button class="reply">Reply</button> <button class="reply-all">Reply to all</button> <button class="fwd">Forward</button> <button class="del">Delete</button> </section> ``` #### Result {{EmbedLiveSample('Using a section without a heading')}} Depending on the content, including a heading could also be good for SEO, so it is an option to consider. ## 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#sectioning_content" >Sectioning content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content">palpable content</a>. </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>{{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#flow_content" >flow content</a >. Note that a <code>&#x3C;section></code> element must not be a descendant of an {{HTMLElement("address")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/region_role" >region</a ></code > if the element has an <a href="https://developer.paciellogroup.com/blog/2017/04/what-is-an-accessible-name/" >accessible name</a >, otherwise <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> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/alert_role"><code>alert</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/alertdialog_role"><code>alertdialog</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/application_role"><code>application</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/banner_role"><code>banner</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role"><code>complementary</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role"><code>contentinfo</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role"><code>dialog</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/feed_role"><code>feed</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/log_role"><code>log</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/main_role"><code>main</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/marquee_role"><code>marquee</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role"><code>navigation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/note_role"><code>note</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/search_role"><code>search</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/status_role"><code>status</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tabpanel_role"><code>tabpanel</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other section-related elements: {{HTMLElement("body")}}, {{HTMLElement("nav")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("address")}} - [Using HTML sections and outlines](/en-US/docs/Web/HTML/Element/Heading_Elements) - [ARIA: Region role](/en-US/docs/Web/Accessibility/ARIA/Roles/region_role) - [Why You Should Choose HTML5 article Over section](https://www.smashingmagazine.com/2020/01/html5-article-section/), by Bruce Lawson
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/figure/index.md
--- title: "<figure>: The Figure with Optional Caption element" slug: Web/HTML/Element/figure page-type: html-element browser-compat: html.elements.figure --- {{HTMLSidebar}} The **`<figure>`** [HTML](/en-US/docs/Web/HTML) element represents self-contained content, potentially with an optional caption, which is specified using the {{HTMLElement("figcaption")}} element. The figure, its caption, and its contents are referenced as a single unit. {{EmbedInteractiveExample("pages/tabbed/figure.html","tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Usually a `<figure>` is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow. - A caption can be associated with the `<figure>` element by inserting a {{HTMLElement("figcaption")}} inside it (as the first or the last child). The first `<figcaption>` element found in the figure is presented as the figure's caption. - The `<figcaption>` provides the {{glossary("accessible description")}} for the parent `<figure>`. ## Examples ### Images ```html <!-- Just an image --> <figure> <img src="favicon-192x192.png" alt="The beautiful MDN logo." /> </figure> <!-- Image with a caption --> <figure> <img src="favicon-192x192.png" alt="The beautiful MDN logo." /> <figcaption>MDN Logo</figcaption> </figure> ``` #### Result {{EmbedLiveSample("Images", "100%", 375)}} ### Code snippets ```html <figure> <figcaption>Get browser details using <code>navigator</code>.</figcaption> <pre> function NavigatorExample() { var txt; txt = "Browser CodeName: " + navigator.appCodeName + "; "; txt+= "Browser Name: " + navigator.appName + "; "; txt+= "Browser Version: " + navigator.appVersion + "; "; txt+= "Cookies Enabled: " + navigator.cookieEnabled + "; "; txt+= "Platform: " + navigator.platform + "; "; txt+= "User-agent header: " + navigator.userAgent + "; "; console.log("NavigatorExample", txt); } </pre> </figure> ``` #### Result {{EmbedLiveSample("Code_snippets", "100%", 250)}} ### Quotations ```html <figure> <figcaption><b>Edsger Dijkstra:</b></figcaption> <blockquote> If debugging is the process of removing software bugs, then programming must be the process of putting them in. </blockquote> </figure> ``` #### Result {{EmbedLiveSample('Quotations')}} ### Poems ```html <figure> <p style="white-space:pre"> Bid me discourse, I will enchant thine ear, Or like a fairy trip upon the green, Or, like a nymph, with long dishevelled hair, Dance on the sands, and yet no footing seen: Love is a spirit all compact of fire, Not gross to sink, but light, and will aspire. </p> <figcaption><cite>Venus and Adonis</cite>, by William Shakespeare</figcaption> </figure> ``` #### Result {{EmbedLiveSample("Poems", "100%", 250)}} ## 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#palpable_content" >palpable content</a >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> A {{HTMLElement("figcaption")}} element, followed by <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >; or flow content followed by a {{HTMLElement("figcaption")}} element; or flow content. </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#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Figure_Role" >figure</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> With no <a href="/en-US/docs/Web/HTML/Element/figcaption">figcaption </a >descendant: <a href="https://www.w3.org/TR/html-aria/#dfn-any-role">any</a>, otherwise no permitted roles </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("figcaption")}} element.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/html/index.md
--- title: "<html>: The HTML Document / Root element" slug: Web/HTML/Element/html page-type: html-element browser-compat: html.elements.html --- {{HTMLSidebar}} The **`<html>`** [HTML](/en-US/docs/Web/HTML) element represents the root (top-level element) of an HTML document, so it is also referred to as the _root element_. All other elements must be descendants of this element. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `manifest` {{deprecated_inline}} - : Specifies the {{glossary("URI")}} of a resource manifest indicating resources that should be cached locally. - `version` {{deprecated_inline}} - : Specifies the version of the HTML {{glossary("Doctype", "Document Type Definition")}} that governs the current document. This attribute is not needed, because it is redundant with the version information in the document type declaration. - `xmlns` - : Specifies the {{glossary("XML")}} {{glossary("Namespace")}} of the document. Default value is `"http://www.w3.org/1999/xhtml"`. This is required in documents parsed with XML {{glossary("parser", "parsers")}}, and optional in text/html documents. ## Example ```html <!doctype html> <html lang="en"> <head> <!-- … --> </head> <body> <!-- … --> </body> </html> ``` ## Accessibility concerns While HTML does not require authors to specify `<html>` element start and ending tags, it is important for authors to do so as it will allow them to specify the [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang) for the webpage. Providing a `lang` attribute with a valid language tag according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}} on the `<html>` element will help screen reading technology determine the proper language to announce. The identifying language tag should describe the language used by the majority of the content of the page. Without it, screen readers will typically default to the operating system's set language, which may cause mispronunciations. Including a valid `lang` declaration on the `<html>` element also ensures that important metadata contained in the page's {{HTMLElement("head")}}, such as the page's {{HTMLElement("title")}}, are also announced properly. - [MDN Understanding WCAG, Guideline 3.1 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.1_%e2%80%94_readable_make_text_content_readable_and_understandable) - [Understanding Success Criterion 3.1.1 | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/language-of-page.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>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> One {{HTMLElement("head")}} element, followed by one {{HTMLElement("body")}} element. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag may be omitted if the first thing inside the <code>&#x3C;html></code> element is not a comment.<br>The end tag may be omitted if the <code>&#x3C;html></code> element is not immediately followed by a comment. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td>None. This is the root element of a document.</td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Document_role" >document</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("HTMLHtmlElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - MathML top-level element: {{MathMLElement("math")}} - SVG top-level element: {{SVGElement("svg")}}
0
data/mdn-content/files/en-us/web/html/element/html
data/mdn-content/files/en-us/web/html/element/html/manifest/index.md
--- title: manifest slug: Web/HTML/Element/html/manifest page-type: html-attribute status: - deprecated browser-compat: html.elements.html.manifest --- {{securecontext_header}}{{Deprecated_Header}} The **`manifest`** attribute of the `<html>` element specifies a URL of an application cache manifest that is downloaded in the early stages of page load. > **Note:** manifest-based caching mechanism has been deprecated. Use [service workers](/en-US/docs/Web/API/Service_Worker_API) instead. The `manifest` attribute only had an effect during early stages of page load, thus changing it via regular DOM interfaces had no effect. The deprecated {{domxref("Window.applicationCache")}} interface was used instead. The attribute functionality has been superceded by the [web app manifest](/en-US/docs/Web/Manifest), an external JSON file associated with the HTML file through a {{HTMLElement("link")}} with [`rel="manifest"`](/en-US/docs/Web/HTML/Attributes/rel). ## Browser compatibility {{Compat}} ## See also - [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) - [`manifest.json`](/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json) - [Web app manifests](/en-US/docs/Web/Manifest) - [Making PWAs installable](/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/style/index.md
--- title: "<style>: The Style Information element" slug: Web/HTML/Element/style page-type: html-element browser-compat: html.elements.style --- {{HTMLSidebar}} The **`<style>`** [HTML](/en-US/docs/Web/HTML) element contains style information for a document, or part of a document. It contains CSS, which is applied to the contents of the document containing the `<style>` element. {{EmbedInteractiveExample("pages/tabbed/style.html", "tabbed-standard")}} The `<style>` element must be included inside the {{htmlelement("head")}} of the document. In general, it is better to put your styles in external stylesheets and apply them using {{htmlelement("link")}} elements. If you include multiple `<style>` and `<link>` elements in your document, they will be applied to the DOM in the order they are included in the document — make sure you include them in the correct order, to avoid unexpected cascade issues. In the same manner as `<link>` elements, `<style>` elements can include `media` attributes that contain [media queries](/en-US/docs/Web/CSS/CSS_media_queries), allowing you to selectively apply internal stylesheets to your document depending on media features such as viewport width. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `blocking` {{Experimental_Inline}} - : This attribute explicitly indicates that certain operations should be blocked on the fetching of critical subresources. [`@import`](/en-US/docs/Web/CSS/@import)-ed stylesheets are generally considered as critical subresources, whereas [`background-image`](/en-US/docs/Web/CSS/background-image) and fonts are not. - `render`: The rendering of content on the screen is blocked. - `media` - : This attribute defines which media the style should be applied to. Its value is a [media query](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries), which defaults to `all` if the attribute is missing. - `nonce` - : A cryptographic nonce (number used once) used to allow inline styles in a [style-src Content-Security-Policy](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-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. - `title` - : This attribute specifies [alternative style sheet](/en-US/docs/Web/CSS/Alternative_style_sheets) sets. ### Deprecated attributes - `type` {{deprecated_inline}} - : This attribute should not be provided: if it is, the only permitted values are the empty string or a case-insensitive match for `text/css`. ## Examples ### A simple stylesheet In the following example, we apply a very simple stylesheet to a document: ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Test page</title> <style> p { color: red; } </style> </head> <body> <p>This is my paragraph.</p> </body> </html> ``` #### Result {{EmbedLiveSample('A_simple_stylesheet', '100%', '100')}} ### Multiple style elements In this example we've included two `<style>` elements — notice how the conflicting declarations in the later `<style>` element override those in the earlier one, if they have equal [specificity](/en-US/docs/Web/CSS/Specificity). ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Test page</title> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; } </style> <style> p { color: blue; background-color: yellow; } </style> </head> <body> <p>This is my paragraph.</p> </body> </html> ``` #### Result {{EmbedLiveSample('Multiple_style_elements', '100%', '100')}} ### Including a media query In this example we build on the previous one, including a `media` attribute on the second `<style>` element so it is only applied when the viewport is less than 500px in width. ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Test page</title> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; } </style> <style media="all and (max-width: 500px)"> p { color: blue; background-color: yellow; } </style> </head> <body> <p>This is my paragraph.</p> </body> </html> ``` #### Result {{EmbedLiveSample('Including_a_media_query', '100%', '100')}} ## 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 >, and if the <code>scoped</code> attribute is present: <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >. </td> </tr> <tr> <th>Permitted content</th> <td> Text content matching the <code>type</code> attribute, that is <code>text/css</code>. </td> </tr> <tr> <th>Tag omission</th> <td>Neither tag is omissible.</td> </tr> <tr> <th>Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content" >metadata 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>DOM interface</th> <td>{{domxref("HTMLStyleElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("link")}} element, which allows us to apply external stylesheets to a document. - [Alternative Style Sheets](/en-US/docs/Web/CSS/Alternative_style_sheets)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/bdo/index.md
--- title: "<bdo>: The Bidirectional Text Override element" slug: Web/HTML/Element/bdo page-type: html-element browser-compat: html.elements.bdo --- {{HTMLSidebar}} The **`<bdo>`** [HTML](/en-US/docs/Web/HTML) element overrides the current directionality of text, so that the text within is rendered in a different direction. {{EmbedInteractiveExample("pages/tabbed/bdo.html", "tabbed-standard")}} The text's characters are drawn from the starting point in the given direction; the individual characters' orientation is not affected (so characters don't get drawn backward, for example). ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `dir` - : The direction in which text should be rendered in this element's contents. Possible values are: - `ltr`: Indicates that the text should go in a left-to-right direction. - `rtl`: Indicates that the text should go in a right-to-left direction. ## Examples ```html <!-- Switch text direction --> <p>This text will go left to right.</p> <p><bdo dir="rtl">This text will go right to left.</bdo></p> ``` ### Result {{EmbedLiveSample('Examples')}} ## Notes The HTML 4 specification did not specify events for this element; they were added in XHTML. This is most likely an oversight. ## 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("HTMLElement")}} Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the <code ><a href="/en-US/docs/Web/API/HTMLSpanElement" >HTMLSpanElement</a ></code > interface for this element. </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related HTML element: {{HTMLElement("bdi")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/tbody/index.md
--- title: "<tbody>: The Table Body element" slug: Web/HTML/Element/tbody page-type: html-element browser-compat: html.elements.tbody --- {{HTMLSidebar}} The **`<tbody>`** [HTML](/en-US/docs/Web/HTML) element encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the body of a table's (main) data. {{EmbedInteractiveExample("pages/tabbed/tbody.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 body 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 body 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 body 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 body cell content from the alignment character specified by the [`char`](#char) attribute. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of each body 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 `<tbody>` is placed after any {{HTMLElement("caption")}}, {{HTMLElement("colgroup")}}, and {{HTMLElement("thead")}} elements. - If {{HTMLElement("tr")}} elements are specified outside an existing `<tbody>` element as direct children of the {{HTMLElement("table")}}, these elements will be encapsulated by a separate `<tbody>` element generated by the browser. - It's permitted to use more than one `<tbody>` per table as long as they are all consecutive. This allows to divide the rows ({{HTMLElement("tr")}} elements) in large tables into sections, each of which may be separately formatted if so desired. If not marked up to be consecutive elements, browsers will correct this author error, ensuring any {{HTMLElement("thead")}} and {{HTMLElement("tfoot")}} elements are rendered as the first and last elements of the table, respectively. - Along with its related {{HTMLElement("thead")}} and {{HTMLElement("tfoot")}} elements, the `<tbody>` element provides useful {{Glossary("semantics", "semantic")}} information and can be used when rendering for either screen or print. Specifying such table content groups also provides valuable contextual information for assistive technologies, including screen readers and search engines. - When printing a document, in the case of a multipage table, the {{HTMLElement("thead")}} and {{htmlelement("tfoot")}} elements usually specify information that remains the same—or at least very similar—on each page, while the `<tbody>` element's contents generally will differ from page to page. - When a table is presented in a screen context (such as a window) that is not large enough to display the entire table, the {{Glossary("user agent")}} may let the user scroll the contents of the {{HTMLElement("thead")}}, `<tbody>`, {{htmlelement("tfoot")}}, and {{HTMLElement("caption")}} blocks separately from one another for the same parent {{htmlelement("table")}}. ## Examples See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. ### Not specifying a body This example demonstrates that the browser automatically encapsulates {{HTMLElement("tr")}} elements within a `<tbody>` element if the rows are not nested within a table grouping element (`<tbody>`, `<tfoot>`, or `<thead>`) and are, as in this example, the direct children of the {{HTMLElement("table")}} element. #### HTML Here, a very basic table with some table rows ({{HTMLElement("tr")}} elements) containing data ({{HTMLElement("td")}} elements) about students is created. ```html <table> <tr> <td>3741255</td> <td>Jones, Martha</td> <td>Computer Science</td> <td>240</td> </tr> <tr> <td>3971244</td> <td>Nim, Victor</td> <td>Russian Literature</td> <td>220</td> </tr> <tr> <td>4100332</td> <td>Petrov, Alexandra</td> <td>Astrophysics</td> <td>260</td> </tr> </table> ``` #### CSS Note the CSS in the example, where a {{cssxref("background-color")}} is specified for the `<tbody>` element and the `tbody` is used as a part of an additional {{Glossary("css_selector", "CSS selector")}}. Alternatively, {{Glossary("developer_tools", "browser developer tools")}} can be used to check the presence of the `<tbody>` element in the {{Glossary("dom", "DOM")}}. ```css tbody { background-color: #e4f0f5; } tbody > tr > td:last-of-type { width: 60px; text-align: center; } ``` ```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: 8px 10px; } ``` #### Result {{EmbedLiveSample("Not_specifying_a_body", 650, 100)}} ### Basic body structure This example extends and enhances the basic table from the [previous example](#not_specifying_a_body). #### HTML We introduce a table head ({{HTMLElement("thead")}} element) and explicitly use a `<tbody>` element to structure the table into {{Glossary("semantics", "semantic")}} sections. The table head contains the column headers ({{HTMLElement("th")}} elements). The `<tbody>` element represents the body section of the table, which contains a number of rows ({{HTMLElement("tr")}} elements) with the table's main data, which is the data of each student. The use of such table content groups and {{Glossary("semantics", "semantic")}} markup is not only useful for visual presentation (via CSS styling) and contextual information for assistive technologies; moreover, the explicit use of the `<tbody>` element helps the browser to create the intended table structure, avoiding unwanted results. ```html <table> <thead> <tr> <th>Student ID</th> <th>Name</th> <th>Major</th> <th>Credits</th> </tr> </thead> <tbody> <tr> <td>3741255</td> <td>Jones, Martha</td> <td>Computer Science</td> <td>240</td> </tr> <tr> <td>3971244</td> <td>Nim, Victor</td> <td>Russian Literature</td> <td>220</td> </tr> <tr> <td>4100332</td> <td>Petrov, Alexandra</td> <td>Astrophysics</td> <td>260</td> </tr> </tbody> </table> ``` #### CSS The CSS is nearly unchanged from the [previous example](#not_specifying_a_body), except for some basic styling to highlight the table head so that the headers of the columns stand out from the data in the table body. As in the [example above](#not_specifying_a_body), the `tbody` [type selector](/en-US/docs/Web/CSS/Type_selectors) is used to style the body cells. ```css tbody { background-color: #e4f0f5; } tbody > tr > td:last-of-type { text-align: center; } thead { border-bottom: 2px solid rgb(160 160 160); background-color: #2c5e77; color: #fff; } ``` ```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_body_structure", 650, 140)}} ### Multiple bodies This example extends and enhances the table from the [example above](#basic_body_structure) even more by introducing multiple body sections. Using multiple `<tbody>` elements allows creating row groupings within a table. Each table body can potentially have its own head row or rows; however, _there may only be one {{HTMLElement("thead")}} element per table_! Because of that, {{HTMLElement("tr")}} with {{HTMLElement("th")}} elements can be used to create headers within each `<tbody>`. #### HTML Building on the table in the [previous basic example](#basic_body_structure), more students are added and, instead of listing each student's major on each row, the students are grouped by major. Note that each major is enclosed within its own `<tbody>` block, with the first row ({{HTMLElement("tr")}} element) serving as the head of the block, displaying the major title within a {{HTMLElement("th")}} element that uses the [`colspan`](/en-US/docs/Web/HTML/Element/th#colspan) attribute to span the header across all three columns of the table. Each remaining row within each major's `<tbody>` represents one student. ```html <table> <thead> <tr> <th>Student ID</th> <th>Name</th> <th>Credits</th> </tr> </thead> <tbody> <tr> <th colspan="3">Computer Science</th> </tr> <tr> <td>3741255</td> <td>Jones, Martha</td> <td>240</td> </tr> <tr> <td>4077830</td> <td>Pierce, Benjamin</td> <td>200</td> </tr> <tr> <td>5151701</td> <td>Kirk, James</td> <td>230</td> </tr> </tbody> <tbody> <tr> <th colspan="3">Russian Literature</th> </tr> <tr> <td>3971244</td> <td>Nim, Victor</td> <td>220</td> </tr> </tbody> <tbody> <tr> <th colspan="3">Astrophysics</th> </tr> <tr> <td>4100332</td> <td>Petrov, Alexandra</td> <td>260</td> </tr> <tr> <td>8892377</td> <td>Toyota, Hiroko</td> <td>240</td> </tr> </tbody> </table> ``` #### CSS Most of the CSS is unchanged. However, a slightly more subtle style is added for header cells contained directly within a `<tbody>` (as opposed to those that reside in the {{HTMLElement("thead")}}). This is used for the headers indicating each table section's corresponding major. ```css tbody > tr > th { border-top: 2px solid rgb(160 160 160); border-bottom: 1px solid rgb(140 140 140); background-color: #e4f0f5; font-weight: normal; } tbody { background-color: whitesmoke; } thead { background-color: #2c5e77; color: #fff; } ``` ```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: 6px 8px; text-align: left; } tbody > tr > td:last-of-type { text-align: center; } ``` #### Result {{EmbedLiveSample("Multiple_bodies", 650, 300)}} ## 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("tr") }} elements.</td> </tr> <tr> <th scope="row">Tag omission</th> <td> A {{HTMLElement("tbody")}} element's start tag can be omitted if the first thing inside the {{HTMLElement("tbody")}} element is a {{HTMLElement("tr")}} element, and if the element is not immediately preceded by a {{HTMLElement("tbody")}}, {{HTMLElement("thead")}}, or {{HTMLElement("tfoot")}} element whose end tag has been omitted. (It can't be omitted if the element is empty.) A {{HTMLElement("tbody")}} element's end tag can be omitted if the {{HTMLElement("tbody")}} element is immediately followed by a {{HTMLElement("tbody")}} or {{HTMLElement("tfoot")}} element, or if there is no more content in the parent element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Within the required parent {{ HTMLElement("table") }} element, the {{HTMLElement("tbody")}} element can be added after any {{ HTMLElement("caption") }}, {{HTMLElement("colgroup") }}, and {{ HTMLElement("thead") }} elements. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Rowgroup_Role" >rowgroup</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("HTMLTableSectionElement")}}</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("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 body cell - {{cssxref("border")}}: CSS property to control borders of body cells - {{cssxref("text-align")}}: CSS property to horizontally align each body cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each body cell content
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/mark/index.md
--- title: "<mark>: The Mark Text element" slug: Web/HTML/Element/mark page-type: html-element browser-compat: html.elements.mark --- {{HTMLSidebar}} The **`<mark>`** [HTML](/en-US/docs/Web/HTML) element represents text which is **marked** or **highlighted** for reference or notation purposes due to the marked passage's relevance in the enclosing context. {{EmbedInteractiveExample("pages/tabbed/mark.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes Typical use cases for `<mark>` include: - When used in a quotation ({{HTMLElement("q")}}) or block quote ({{HTMLElement("blockquote")}}), it generally indicates text which is of special interest but is not marked in the original source material, or material which needs special scrutiny even though the original author didn't think it was of particular importance. Think of this like using a highlighter pen in a book to mark passages that you find of interest. - Otherwise, `<mark>` indicates a portion of the document's content which is likely to be relevant to the user's current activity. This might be used, for example, to indicate the words that matched a search operation. - Don't use `<mark>` for syntax highlighting purposes; instead, use the {{HTMLElement("span")}} element with appropriate CSS applied to it. > **Note:** Don't confuse `<mark>` with the {{HTMLElement("strong")}} element; `<mark>` is used to denote content which has a degree of _relevance_, while `<strong>` indicates spans of text of _importance_. ## Examples ### Marking text of interest In this first example, a `<mark>` element is used to mark some text within a quote which is of particular interest to the user. ```html <blockquote> It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire. During the battle, <mark>Rebel spies managed to steal secret plans</mark> to the Empire's ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet. </blockquote> ``` #### Result {{EmbedLiveSample("Marking_text_of_interest", 650, 130)}} ### Identifying context-sensitive passages This example demonstrates using `<mark>` to mark search results within a passage. ```html <p> It is a dark time for the Rebellion. Although the Death Star has been destroyed, <mark class="match">Imperial</mark> troops have driven the Rebel forces from their hidden base and pursued them across the galaxy. </p> <p> Evading the dreaded <mark class="match">Imperial</mark> Starfleet, a group of freedom fighters led by Luke Skywalker has established a new secret base on the remote ice world of Hoth. </p> ``` To help distinguish the use of `<mark>` for search results from other potential usage, this example applies the custom class `"match"` to each match. #### Result {{EmbedLiveSample("Identifying_context-sensitive_passages", 650, 130)}} ## Accessibility concerns The presence of the `mark` 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 mark::before, mark::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } mark::before { content: " [highlight start] "; } mark::after { content: " [highlight 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 highlighted 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#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/em/index.md
--- title: "<em>: The Emphasis element" slug: Web/HTML/Element/em page-type: html-element browser-compat: html.elements.em --- {{HTMLSidebar}} The **`<em>`** [HTML](/en-US/docs/Web/HTML) element marks text that has stress emphasis. The `<em>` element can be nested, with each level of nesting indicating a greater degree of emphasis. {{EmbedInteractiveExample("pages/tabbed/em.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<em>` element is for words that have a stressed emphasis compared to surrounding text, which is often limited to a word or words of a sentence and affects the meaning of the sentence itself. Typically this element is displayed in italic type. However, it should not be used to apply italic styling; use the CSS {{cssxref("font-style")}} property for that purpose. Use the {{HTMLElement("cite")}} element to mark the title of a work (book, play, song, etc.). Use the {{HTMLElement("i")}} element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages. Use the {{HTMLElement("strong")}} element to mark text that has greater importance than surrounding text. ### \<i> vs. \<em> Some developers may be confused by how multiple elements seemingly produce similar visual results. `<em>` and `<i>` are a common example, since they both italicize text. What's the difference? Which should you use? By default, the visual result is the same. However, the semantic meaning is different. The `<em>` element represents stress emphasis of its contents, while the `<i>` element represents text that is set off from the normal prose, such as a foreign word, fictional character thoughts, or when the text refers to the definition of a word instead of representing its semantic meaning. (The title of a work, such as the name of a book or movie, should use `<cite>`.) This means the right one to use depends on the situation. Neither is for purely decorative purposes, that's what CSS styling is for. An example for `<em>` could be: "Just _do_ it already!", or: "We _had_ to do something about it". A person or software reading the text would pronounce the words in italics with an emphasis, using verbal stress. An example for `<i>` could be: "The _Queen Mary_ sailed last night". Here, there is no added emphasis or importance on the word "Queen Mary". It is merely indicated that the object in question is not a queen named Mary, but a ship named _Queen Mary_. Another example for `<i>` could be: "The word _the_ is an article". ## Examples In this example, the `<em>` element is used to highlight an implicit or explicit contrast between two ingredient lists: ```html <p> Ice cream is made with milk, sweetener, and cream. Frozen custard, on the other hand, is made of milk, cream, sweetener, and <em>egg yolks</em>. </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/structural_roles#structural_roles_with_html_equivalents">emphasis</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")}} 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("i")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/legend/index.md
--- title: "<legend>: The Field Set Legend element" slug: Web/HTML/Element/legend page-type: html-element browser-compat: html.elements.legend --- {{HTMLSidebar}} The **`<legend>`** [HTML](/en-US/docs/Web/HTML) element represents a caption for the content of its parent {{HTMLElement("fieldset")}}. {{EmbedInteractiveExample("pages/tabbed/legend.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples See {{HTMLElement("form")}} for examples on `<legend>`. ## 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#phrasing_content" >Phrasing content</a > and <a href="/en-US/docs/Web/HTML/Element/Heading_Elements">headings</a> (h1–h6 elements). </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("fieldset")}} whose first child is this <code>&#x3C;legend></code> 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("HTMLLegendElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ARIA: Form role](/en-US/docs/Web/Accessibility/ARIA/Roles/form_role)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/strike/index.md
--- title: <strike> slug: Web/HTML/Element/strike page-type: html-element status: - deprecated browser-compat: html.elements.strike --- {{HTMLSidebar}}{{deprecated_header}} The **`<strike>`** [HTML](/en-US/docs/Web/HTML) element places a strikethrough (horizontal line) over text. > **Warning:** This element is deprecated in HTML 4 and XHTML 1, and obsoleted in the [HTML Living Standard](https://html.spec.whatwg.org/multipage/obsolete.html#strike). If semantically appropriate, i.e., if it represents _deleted_ content, use {{HTMLElement("del")}} instead. In all other cases use {{HTMLElement("s")}}. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ```html &lt;strike&gt;: <strike>Today's Special: Salmon</strike> SOLD OUT<br /> &lt;s&gt;: <s>Today's Special: Salmon</s> SOLD OUT ``` ### Result {{EmbedLiveSample("Example")}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("s")}} element. - The {{HTMLElement("del")}} element should be used if the data has been _deleted_. - The CSS {{CSSxRef("text-decoration")}} property can be used to style text with a strikethrough.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/audio/index.md
--- title: "<audio>: The Embed Audio element" slug: Web/HTML/Element/audio page-type: html-element browser-compat: html.elements.audio --- {{HTMLSidebar}} The **`<audio>`** [HTML](/en-US/docs/Web/HTML) element is used to embed sound content in documents. It may contain one or more audio sources, represented using the `src` attribute or the {{HTMLElement("source")}} element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a {{domxref("MediaStream")}}. {{EmbedInteractiveExample("pages/tabbed/audio.html","tabbed-standard")}} The above example shows simple usage of the `<audio>` element. In a similar manner to the {{htmlelement("img")}} element, we include a path to the media we want to embed inside the `src` attribute; we can include other attributes to specify information such as whether we want it to autoplay and loop, whether we want to show the browser's default audio controls, etc. The content inside the opening and closing `<audio></audio>` tags is shown as a fallback in browsers that don't support the element. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `autoplay` - : A Boolean attribute: if specified, the audio will automatically begin playback as soon as it can do so, without waiting for the entire audio file to finish downloading. > **Note:** Sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, this can be useful when creating media elements whose source will be set at a later time, under user control. See our [autoplay guide](/en-US/docs/Web/Media/Autoplay_guide) for additional information about how to properly use autoplay. - `controls` - : If this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, and pause/resume playback. - `controlslist` - : The [`controlslist`](https://wicg.github.io/controls-list/explainer.html) attribute, when specified, helps the browser select what controls to show for the `audio` element whenever the browser shows its own set of controls (that is, when the `controls` attribute is specified). The allowed values are `nodownload`, `nofullscreen` and `noremoteplayback`. - `crossorigin` - : This [enumerated](/en-US/docs/Glossary/Enumerated) attribute indicates whether to use CORS to fetch the related audio file. [CORS-enabled resources](/en-US/docs/Web/HTML/CORS_enabled_image) can be reused in the {{HTMLElement("canvas")}} element without being _tainted_. The allowed values are: - `anonymous` - : Sends a cross-origin request without a credential. In other words, it sends the `Origin:` HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the `Access-Control-Allow-Origin:` HTTP header), the resource will be _tainted_, and its usage restricted. - `use-credentials` - : Sends a cross-origin request with a credential. In other words, it sends the `Origin:` HTTP header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through `Access-Control-Allow-Credentials:` HTTP header), the resource will be _tainted_ and its usage restricted. When not present, the resource is fetched without a CORS request (i.e. without sending the `Origin:` HTTP header), preventing its non-tainted use in {{HTMLElement('canvas')}} elements. If invalid, it is handled as if the enumerated keyword **anonymous** was used. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for additional information. - `disableremoteplayback` - : A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc.). See [this proposed specification](https://www.w3.org/TR/remote-playback/#the-disableremoteplayback-attribute) for more information. In Safari, you can use [`x-webkit-airplay="deny"`](https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/AirPlayGuide/OptingInorOutofAirPlay/OptingInorOutofAirPlay.html) as a fallback. - `loop` - : A Boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio. - `muted` - : A Boolean attribute that indicates whether the audio will be initially silenced. Its default value is `false`. - `preload` - : This [enumerated](/en-US/docs/Glossary/Enumerated) attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience. It may have one of the following values: - `none`: Indicates that the audio should not be preloaded. - `metadata`: Indicates that only audio metadata (e.g. length) is fetched. - `auto`: Indicates that the whole audio file can be downloaded, even if the user is not expected to use it. - _empty string_: A synonym of the `auto` value. The default value is different for each browser. The spec advises it to be set to `metadata`. > **Note:** > > - The `autoplay` attribute has precedence over `preload`. If `autoplay` is specified, the browser would obviously need to start downloading the audio for playback. > - The browser is not forced by the specification to follow the value of this attribute; it is a mere hint. - `src` - : The URL of the audio to embed. This is subject to [HTTP access controls](/en-US/docs/Web/HTTP/CORS). This is optional; you may instead use the {{htmlelement("source")}} element within the audio block to specify the audio to embed. ## Events <table class="no-markdown"> <thead> <tr> <th scope="col">Event name</th> <th scope="col">Fired when</th> </tr> </thead> <tbody> <tr> <td>{{domxref("ScriptProcessorNode/audioprocess_event", "audioprocess")}}</td> <td> The input buffer of a {{DOMxRef("ScriptProcessorNode")}} is ready to be processed. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} </td> <td> The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} </td> <td> The browser estimates it can play the media up to its end without stopping for content buffering. </td> </tr> <tr> <td>{{domxref("OfflineAudioContext/complete_event", "complete")}}</td> <td> The rendering of an {{DOMxRef("OfflineAudioContext")}} is terminated. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} </td> <td>The <code>duration</code> attribute has been updated.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} </td> <td> The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the {{domxref("HTMLMediaElement.load")}} method is called to reload it. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.ended_event", 'ended')}} </td> <td>Playback has stopped because the end of the media was reached.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} </td> <td>The first frame of the media has finished loading.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} </td> <td>The metadata has been loaded.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.loadstart_event", 'loadstart')}} </td> <td>Fired when the browser has started to load the resource.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.pause_event", 'pause')}} </td> <td>Playback has been paused.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.play_event", 'play')}} </td> <td>Playback has begun.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.playing_event", 'playing')}} </td> <td> Playback is ready to start after having been paused or delayed due to lack of data. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} </td> <td>The playback rate has changed.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} </td> <td>A <em>seek</em> operation completed.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} </td> <td>A <em>seek</em> operation began.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} </td> <td> The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} </td> <td>Media data loading has been suspended.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} </td> <td> The time indicated by the <code>currentTime</code> attribute has been updated. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} </td> <td>The volume has changed.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} </td> <td>Playback has stopped because of a temporary lack of data</td> </tr> </tbody> </table> ## Usage notes Browsers don't all support the same [file types](/en-US/docs/Web/Media/Formats/Containers) and [audio codecs](/en-US/docs/Web/Media/Formats/Audio_codecs); you can provide multiple sources inside nested {{htmlelement("source")}} elements, and the browser will then use the first one it understands: ```html <audio controls> <source src="myAudio.mp3" type="audio/mpeg" /> <source src="myAudio.ogg" type="audio/ogg" /> <p> Download <a href="myAudio.mp3" download="myAudio.mp3">MP3</a> or <a href="myAudio.ogg" download="myAudio.ogg">OGG</a> audio. </p> </audio> ``` We offer a substantive and thorough [guide to media file types](/en-US/docs/Web/Media/Formats) and the [audio codecs that can be used within them](/en-US/docs/Web/Media/Formats/Audio_codecs). Also available is [a guide to the codecs supported for video](/en-US/docs/Web/Media/Formats/Video_codecs). Other usage notes: - If you don't specify the `controls` attribute, the audio player won't include the browser's default controls. You can, however, create your own custom controls using JavaScript and the {{domxref("HTMLMediaElement")}} API. - To allow precise control over your audio content, `HTMLMediaElement`s fire many different [events](/en-US/docs/Web/API/HTMLMediaElement#events). This also provides a way to monitor the audio's fetching process so you can watch for errors or detect when enough is available to begin to play or manipulate it. - You can also use the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) to directly generate and manipulate audio streams from JavaScript code rather than streaming pre-existing audio files. - `<audio>` elements can't have subtitles or captions associated with them in the same way that `<video>` elements can. See [WebVTT and Audio](https://www.iandevlin.com/blog/2015/12/html5/webvtt-and-audio/) by Ian Devlin for some useful information and workarounds. - To test the fallback content on browsers that support the element, you can replace `<audio>` with a non-existing element like `<notanaudio>`. A good general source of information on using HTML `<audio>` is the [Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) beginner's tutorial. ### Styling with CSS The `<audio>` element has no intrinsic visual output of its own unless the `controls` attribute is specified, in which case the browser's default controls are shown. The default controls have a {{cssxref("display")}} value of `inline` by default, and it is often a good idea to set the value to `block` to improve control over positioning and layout, unless you want it to sit within a text block or similar. You can style the default controls with properties that affect the block as a single unit, so for example you can give it a {{cssxref("border")}} and {{cssxref("border-radius")}}, {{cssxref("padding")}}, {{cssxref("margin")}}, etc. You can't however style the individual components inside the audio player (e.g. change the button size or icons, change the font, etc.), and the controls are different across the different browsers. To get a consistent look and feel across browsers, you'll need to create custom controls; these can be marked up and styled in whatever way you want, and then JavaScript can be used along with the {{domxref("HTMLMediaElement")}} API to wire up their functionality. [Video player styling basics](/en-US/docs/Web/Media/Audio_and_video_delivery/Video_player_styling_basics) provides some useful styling techniques — it is written in the context of `<video>`, but much of it is equally applicable to `<audio>`. ### Detecting addition and removal of tracks You can detect when tracks are added to and removed from an `<audio>` element using the {{domxref("AudioTrackList/addtrack_event", "addtrack")}} and {{domxref("AudioTrackList/removetrack_event", "removetrack")}} events. However, these events aren't sent directly to the `<audio>` element itself. Instead, they're sent to the track list object within the `<audio>` element's {{domxref("HTMLMediaElement")}} that corresponds to the type of track that was added to the element: - {{domxref("HTMLMediaElement.audioTracks")}} - : An {{domxref("AudioTrackList")}} containing all of the media element's audio tracks. You can add a listener for `addtrack` to this object to be alerted when new audio tracks are added to the element. - {{domxref("HTMLMediaElement.videoTracks")}} - : Add an `addtrack` listener to this {{domxref("VideoTrackList")}} object to be informed when video tracks are added to the element. - {{domxref("HTMLMediaElement.textTracks")}} - : Add an `addtrack` event listener to this {{domxref("TextTrackList")}} to be notified when new text tracks are added to the element. > **Note:** Even though it's an `<audio>` element, it still has video and text track lists, and can in fact be used to present video, although the user interface implications can be odd. For example, to detect when audio tracks are added to or removed from an `<audio>` element, you can use code like this: ```js const elem = document.querySelector("audio"); elem.audioTrackList.onaddtrack = (event) => { trackEditor.addTrack(event.track); }; elem.audioTrackList.onremovetrack = (event) => { trackEditor.removeTrack(event.track); }; ``` This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. You can also use {{domxref("EventTarget.addEventListener", "addEventListener()")}} to listen for the {{domxref("AudioTrackList/addtrack_event", "addtrack")}} and {{domxref("AudioTrackList/removetrack_event", "removetrack")}} events. ## Examples ### Basic usage The following example shows simple usage of the `<audio>` element to play an OGG file. It will autoplay due to the `autoplay` attribute—if the page has permission to do so—and also includes fallback content. ```html <!-- Simple audio playback --> <audio src="AudioTest.ogg" autoplay> <a href="AudioTest.ogg" download="AudioTest.ogg">Download OGG audio</a>. </audio> ``` For details on when autoplay works, how to get permission to use autoplay, and how and when it's appropriate to use autoplay, see our [autoplay guide](/en-US/docs/Web/Media/Autoplay_guide). ### \<audio> element with \<source> element This example specifies which audio track to embed using the `src` attribute on a nested `<source>` element rather than directly on the `<audio>` element. It is always useful to include the file's MIME type inside the `type` attribute, as the browser is able to instantly tell if it can play that file, and not waste time on it if not. ```html <audio controls> <source src="foo.wav" type="audio/wav" /> <a href="foo.wav" download="foo.wav">Download WAV audio</a>. </audio> ``` ### \<audio> with multiple \<source> elements This example includes multiple `<source>` elements. The browser tries to load the first source element (Opus) if it is able to play it; if not it falls back to the second (Vorbis) and finally back to MP3: ```html <audio controls> <source src="foo.opus" type="audio/ogg; codecs=opus" /> <source src="foo.ogg" type="audio/ogg; codecs=vorbis" /> <source src="foo.mp3" type="audio/mpeg" /> </audio> ``` ## Accessibility concerns Audio with spoken dialog should provide both captions and transcripts that accurately describe its content. Captions, which are specified using [WebVTT](/en-US/docs/Web/API/WebVTT_API), allow people who are hearing impaired to understand an audio recording's content as the recording is being played, while transcripts allow people who need additional time to be able to review the recording's content at a pace and format that is comfortable for them. If automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source audio. The `<audio>` element doesn't directly support WebVTT. You will have to find a library or framework that provides the capability for you, or write the code to display captions yourself. One option is to play your audio using a {{HTMLElement("video")}} element, which does support WebVTT. In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone. For example, in the WebVTT below, note the use of square brackets to provide tone and emotional insight to the viewer; this can help establish the mood otherwise provided using music, nonverbal sounds and crucial sound effects, and so forth. ```plain 1 00:00:00 --> 00:00:45 [Energetic techno music] 2 00:00:46 --> 00:00:51 Welcome to the Time Keeper's podcast! In this episode we're discussing which Swisswatch is a wrist switchwatch? 16 00:00:52 --> 00:01:02 [Laughing] Sorry! I mean, which wristwatch is a Swiss wristwatch? ``` Also it's a good practice to provide some content (such as the direct download link) as a fallback for viewers who use a browser in which the `<audio>` element is not supported: ```html <audio controls> <source src="myAudio.mp3" type="audio/mpeg" /> <source src="myAudio.ogg" type="audio/ogg" /> <p> Download <a href="myAudio.mp3">MP3</a> or <a href="myAudio.ogg" download="myAudio.ogg">OGG</a> audio. </p> </audio> ``` - [Web Video Text Tracks Format (WebVTT)](/en-US/docs/Web/API/WebVTT_API) - [WebAIM: Captions, Transcripts, and Audio Descriptions](https://webaim.org/techniques/captions/) - [MDN Understanding WCAG, Guideline 1.2 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.2_—_providing_text_alternatives_for_time-based_media) - [Understanding Success Criterion 1.2.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-av-only-alt.html) - [Understanding Success Criterion 1.2.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-captions.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#flow_content" >Flow content</a >, phrasing content, embedded content. If it has a <a href="/en-US/docs/Web/HTML/Element/audio#controls"><code>controls</code></a> attribute: interactive content and palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> If the element has a <a href="/en-US/docs/Web/HTML/Element/audio#src"><code>src</code></a> attribute: zero or more {{HTMLElement("track")}} elements followed by transparent content that contains no {{HTMLElement("audio")}} or {{HTMLElement("video")}} media elements.<br />Else: zero or more {{HTMLElement("source")}} elements followed by zero or more {{HTMLElement("track")}} elements followed by transparent content that contains no {{HTMLElement("audio")}} or {{HTMLElement("video")}} media elements. </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 embedded content.</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></td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLAudioElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web media technologies](/en-US/docs/Web/Media) - [Media container formats (file types)](/en-US/docs/Web/Media/Formats/Containers) - [Guide to audio codecs used on the web](/en-US/docs/Web/Media/Formats/Audio_codecs) - [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) - {{domxref("HTMLAudioElement")}} - {{htmlelement("source")}} - {{htmlelement("video")}} - [Learning area: Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) - [Cross-browser audio basics](/en-US/docs/Web/Media/Audio_and_video_delivery/Cross-browser_audio_basics)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/link/index.md
--- title: "<link>: The External Resource Link element" slug: Web/HTML/Element/link page-type: html-element browser-compat: html.elements.link --- {{HTMLSidebar}} The **`<link>`** [HTML](/en-US/docs/Web/HTML) element specifies relationships between the current document and an external resource. This element is most commonly used to link to {{Glossary("CSS", "stylesheets")}}, but is also used to establish site icons (both "favicon" style icons and icons for the home screen and apps on mobile devices) among other things. {{EmbedInteractiveExample("pages/tabbed/link.html", "tabbed-shorter")}} To link an external stylesheet, you'd include a `<link>` element inside your {{HTMLElement("head")}} like this: ```html <link href="main.css" rel="stylesheet" /> ``` This simple example provides the path to the stylesheet inside an `href` attribute, and a [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute with a value of `stylesheet`. The `rel` stands for "relationship", and is one of the key features of the `<link>` element — the value denotes how the item being linked to is related to the containing document. There are a number of other common types you'll come across. For example, a link to the site's favicon: ```html <link rel="icon" href="favicon.ico" /> ``` There are a number of other icon `rel` values, mainly used to indicate special icon types for use on various mobile platforms, e.g.: ```html <link rel="apple-touch-icon" sizes="114x114" href="apple-icon-114.png" type="image/png" /> ``` The `sizes` attribute indicates the icon size, while the `type` contains the MIME type of the resource being linked. These provide useful hints to allow the browser to choose the most appropriate icon available. You can also provide a media type or query inside a `media` attribute; this resource will then only be loaded if the media condition is true. For example: ```html <link href="print.css" rel="stylesheet" media="print" /> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)" /> ``` Some interesting new performance and security features have been added to the `<link>` element too. Take this example: ```html <link rel="preload" href="myFont.woff2" as="font" type="font/woff2" crossorigin="anonymous" /> ``` A `rel` value of `preload` indicates that the browser should preload this resource (see [`rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload) for more details), with the `as` attribute indicating the specific class of content being fetched. The `crossorigin` attribute indicates whether the resource should be fetched with a {{Glossary("CORS")}} request. Other usage notes: - A `<link>` element can occur either in the {{HTMLElement("head")}} or {{HTMLElement("body")}} element, depending on whether it has a [link type](https://html.spec.whatwg.org/multipage/links.html#body-ok) that is **body-ok**. For example, the `stylesheet` link type is body-ok, and therefore `<link rel="stylesheet">` is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your `<link>` elements from your body content, putting them in the `<head>`. - When using `<link>` to establish a favicon for a site, and your site uses a Content Security Policy (CSP) to enhance its security, the policy applies to the favicon. If you encounter problems with the favicon not loading, verify that the {{HTTPHeader("Content-Security-Policy")}} header's [`img-src` directive](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/img-src) is not preventing access to it. - The HTML and XHTML specifications define event handlers for the `<link>` element, but it is unclear how they would be used. - Under XHTML 1.0, {{glossary("void element", "void elements")}} such as `<link>` require a trailing slash: `<link />`. - WebTV supports the use of the value `next` for `rel` to preload the next page in a document series. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `as` - : This attribute is required when [`rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload) has been set on the `<link>` element, optional when [`rel="modulepreload"`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload) has been set, and otherwise should not be used. It specifies the type of content being loaded by the `<link>`, which is necessary for request matching, application of correct [content security policy](/en-US/docs/Web/HTTP/CSP), and setting of correct {{HTTPHeader("Accept")}} request header. Furthermore, `rel="preload"` uses this as a signal for request prioritization. The table below lists the valid values for this attribute and the elements or resources they apply to. <table class="standard-table"> <thead> <tr> <th scope="col">Value</th> <th scope="col">Applies To</th> </tr> </thead> <tbody> <tr> <td>audio</td> <td><code>&#x3C;audio></code> elements</td> </tr> <tr> <td>document</td> <td><code>&#x3C;iframe></code> and <code>&#x3C;frame></code> elements</td> </tr> <tr> <td>embed</td> <td><code>&#x3C;embed></code> elements</td> </tr> <tr> <td>fetch</td> <td> <p>fetch, XHR</p> <div class="notecard note"> <p> <strong>Note:</strong> This value also requires <code>&#x3C;link></code> to contain the crossorigin attribute, see <a href="/en-US/docs/Web/HTML/Attributes/rel/preload#cors-enabled_fetches">CORS-enabled fetches</a>. </p> </div> </td> </tr> <tr> <td>font</td> <td> <p>CSS @font-face</p> <div class="notecard note"> <p> <strong>Note:</strong> This value also requires <code>&#x3C;link></code> to contain the crossorigin attribute, see <a href="/en-US/docs/Web/HTML/Attributes/rel/preload#cors-enabled_fetches">CORS-enabled fetches</a>. </p> </div> </td> </tr> <tr> <td>image</td> <td> <code>&#x3C;img></code> and <code>&#x3C;picture></code> elements with srcset or imageset attributes, SVG <code>&#x3C;image></code> elements, CSS <code>*-image</code> rules </td> </tr> <tr> <td>object</td> <td><code>&#x3C;object></code> elements</td> </tr> <tr> <td>script</td> <td> <code>&#x3C;script></code> elements, Worker <code>importScripts</code> </td> </tr> <tr> <td>style</td> <td> <code>&#x3C;link rel=stylesheet></code> elements, CSS <code>@import</code> </td> </tr> <tr> <td>track</td> <td><code>&#x3C;track></code> elements</td> </tr> <tr> <td>video</td> <td><code>&#x3C;video></code> elements</td> </tr> <tr> <td>worker</td> <td>Worker, SharedWorker</td> </tr> </tbody> </table> - `blocking` {{Experimental_Inline}} - : This attribute explicitly indicates that certain operations should be blocked on the fetching of an external resource. 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` - : This [enumerated](/en-US/docs/Glossary/Enumerated) attribute indicates whether {{Glossary("CORS")}} must be used when fetching the resource. [CORS-enabled images](/en-US/docs/Web/HTML/CORS_enabled_image) can be reused in the {{HTMLElement("canvas")}} element without being _tainted_. The allowed values are: - `anonymous` - : A cross-origin request (i.e. with an {{HTTPHeader("Origin")}} HTTP header) is performed, but no credential is sent (i.e. no cookie, X.509 certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (by not setting the {{HTTPHeader("Access-Control-Allow-Origin")}} HTTP header) the resource will be tainted and its usage restricted. - `use-credentials` - : A cross-origin request (i.e. with an `Origin` HTTP header) is performed along with a credential sent (i.e. a cookie, certificate, and/or HTTP Basic authentication is performed). If the server does not give credentials to the origin site (through {{HTTPHeader("Access-Control-Allow-Credentials")}} HTTP header), the resource will be _tainted_ and its usage restricted. If the attribute is not present, the resource is fetched without a {{Glossary("CORS")}} request (i.e. without sending the `Origin` HTTP header), preventing its non-tainted usage. If invalid, it is handled as if the enumerated keyword **anonymous** was used. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for additional information. - `disabled` {{Non-standard_Inline}} - : For `rel="stylesheet"` only, the `disabled` Boolean attribute indicates whether the described stylesheet should be loaded and applied to the document. If `disabled` is specified in the HTML when it is loaded, the stylesheet will not be loaded during page load. Instead, the stylesheet will be loaded on-demand, if and when the `disabled` attribute is changed to `false` or removed. Setting the `disabled` property in the DOM causes the stylesheet to be removed from the document's {{domxref("Document.styleSheets")}} list. - `fetchpriority` - : Provides a hint of the relative priority to use when fetching a preloaded resource. Allowed values: - `high` - : Signals a high-priority fetch relative to other resources of the same type. - `low` - : Signals a low-priority fetch relative to other resources of the same type. - `auto` - : Default: Signals automatic determination of fetch priority relative to other resources of the same type. - `href` - : This attribute specifies the {{glossary("URL")}} of the linked resource. A URL can be absolute or relative. - `hreflang` - : This attribute indicates the language of the linked resource. It is purely advisory. Allowed values are specified by {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. Use this attribute only if the [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute is present. - `imagesizes` - : For `rel="preload"` and `as="image"` only, the `imagesizes` attribute is [a sizes attribute](https://html.spec.whatwg.org/multipage/images.html#sizes-attribute) that indicates to preload the appropriate resource used by an `img` element with corresponding values for its `srcset` and `sizes` attributes. - `imagesrcset` - : For `rel="preload"` and `as="image"` only, the `imagesrcset` attribute is [a sourceset attribute](https://html.spec.whatwg.org/multipage/images.html#srcset-attribute) that indicates to preload the appropriate resource used by an `img` element with corresponding values for its `srcset` and `sizes` attributes. - `integrity` - : Contains inline metadata — a base64-encoded cryptographic hash of the resource (file) you're telling the browser to fetch. The browser can use this to verify that the fetched resource has been delivered free of unexpected manipulation. See [Subresource Integrity](/en-US/docs/Web/Security/Subresource_Integrity). - `media` - : This attribute specifies the media that the linked resource applies to. Its value must be a media type / [media query](/en-US/docs/Web/CSS/CSS_media_queries). This attribute is mainly useful when linking to external stylesheets — it allows the user agent to pick the best adapted one for the device it runs on. - `referrerpolicy` - : A string indicating which referrer to use when fetching the resource: - `no-referrer` means that the {{HTTPHeader("Referer")}} header will not be sent. - `no-referrer-when-downgrade` means that no {{HTTPHeader("Referer")}} header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent's default behavior, if no policy is otherwise specified. - `origin` means that the referrer will be the origin of the page, which is roughly the scheme, the host, and the port. - `origin-when-cross-origin` means that navigating to other origins will be limited to the scheme, the host, and the port, while navigating on the same origin will include the referrer's path. - `unsafe-url` means that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe because it can leak origins and paths from TLS-protected resources to insecure origins. - `rel` - : This attribute names a relationship of the linked document to the current document. The attribute must be a space-separated list of [link type values](/en-US/docs/Web/HTML/Attributes/rel). - `sizes` - : This attribute defines the sizes of the icons for visual media contained in the resource. It must be present only if the [`rel`](#rel) contains a value of `icon` or a non-standard type such as Apple's `apple-touch-icon`. It may have the following values: - `any`, meaning that the icon can be scaled to any size as it is in a vector format, like `image/svg+xml`. - a white-space separated list of sizes, each in the format `<width in pixels>x<height in pixels>` or `<width in pixels>X<height in pixels>`. Each of these sizes must be contained in the resource. > **Note:** Most icon formats are only able to store one single icon; therefore, most of the time, the [`sizes`](#sizes) attribute contains only one entry. > MS's ICO format does, as well as Apple's ICNS. ICO is more ubiquitous, so you should use this format if cross-browser support is a concern (especially for old IE versions). - `title` - : The `title` attribute has special semantics on the `<link>` element. When used on a `<link rel="stylesheet">` it defines a [default or an alternate stylesheet](/en-US/docs/Web/CSS/Alternative_style_sheets). - `type` - : This attribute is used to define the type of the content linked to. The value of the attribute should be a MIME type such as **text/html**, **text/css**, and so on. The common use of this attribute is to define the type of stylesheet being referenced (such as **text/css**), but given that CSS is the only stylesheet language used on the web, not only is it possible to omit the `type` attribute, but is actually now recommended practice. It is also used on `rel="preload"` link types, to make sure the browser only downloads file types that it supports. ### Non-standard attributes - `methods` {{Non-standard_Inline}} {{Deprecated_Inline}} - : The value of this attribute provides information about the functions that might be performed on an object. The values generally are given by the HTTP protocol when it is used, but it might (for similar reasons as for the **title** attribute) be useful to include advisory information in advance in the link. For example, the browser might choose a different rendering of a link as a function of the methods specified; something that is searchable might get a different icon, or an outside link might render with an indication of leaving the current site. This attribute is not well understood nor supported, even by the defining browser, Internet Explorer 4. - `target` {{Deprecated_Inline}} - : Defines the frame or window name that has the defined linking relationship or that will show the rendering of any linked resource. ### Obsolete attributes - `charset` {{deprecated_inline}} - : This attribute defines the character encoding of the linked resource. The value is a space- and/or comma-delimited list of character sets as defined in {{rfc(2045)}}. The default value is `iso-8859-1`. > **Note:** To produce the same effect as this obsolete attribute, use the {{HTTPHeader("Content-Type")}} HTTP header on the linked resource. - `rev` {{deprecated_inline}} - : The value of this attribute shows the relationship of the current document to the linked document, as defined by the [`href`](#href) attribute. The attribute thus defines the reverse relationship compared to the value of the `rel` attribute. [Link type values](/en-US/docs/Web/HTML/Attributes/rel) for the attribute are similar to the possible values for [`rel`](#rel). > **Note:** Instead of `rev`, you should use the [`rel`](#rel) attribute with the opposite [link type value](/en-US/docs/Web/HTML/Attributes/rel). > For example, to establish the reverse link for `made`, specify `author`. Also, this attribute doesn't stand for "revision" and must not be used with a version number, even though many sites misuse it in this way. ## Examples ### Including a stylesheet To include a stylesheet in a page, use the following syntax: ```html <link href="style.css" rel="stylesheet" /> ``` ### Providing alternative stylesheets You can also specify [alternative style sheets](/en-US/docs/Web/CSS/Alternative_style_sheets). The user can choose which style sheet to use by choosing it from the **View > Page Style** menu. This provides a way for users to see multiple versions of a page. ```html <link href="default.css" rel="stylesheet" title="Default Style" /> <link href="fancy.css" rel="alternate stylesheet" title="Fancy" /> <link href="basic.css" rel="alternate stylesheet" title="Basic" /> ``` ### Providing icons for different usage contexts You can include links to several icons on the same page, and the browser will choose which one works best for its particular context using the `rel` and `sizes` values as hints. ```html <!-- third-generation iPad with high-resolution Retina display: --> <link rel="apple-touch-icon" sizes="144x144" href="favicon144.png" /> <!-- iPhone with high-resolution Retina display: --> <link rel="apple-touch-icon" sizes="114x114" href="favicon114.png" /> <!-- first- and second-generation iPad: --> <link rel="apple-touch-icon" sizes="72x72" href="favicon72.png" /> <!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: --> <link rel="apple-touch-icon" href="favicon57.png" /> <!-- basic favicon --> <link rel="icon" href="favicon32.png" /> ``` ### Conditionally loading resources with media queries You can provide a media type or query inside a `media` attribute; this resource will then only be loaded if the media condition is true. For example: ```html <link href="print.css" rel="stylesheet" media="print" /> <link href="mobile.css" rel="stylesheet" media="all" /> <link href="desktop.css" rel="stylesheet" media="screen and (min-width: 600px)" /> <link href="highres.css" rel="stylesheet" media="screen and (min-resolution: 300dpi)" /> ``` ### Stylesheet load events You can determine when a style sheet has been loaded by watching for a `load` event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an `error` event: ```html <script> const stylesheet = document.querySelector("#my-stylesheet"); stylesheet.onload = () => { // Do something interesting; the sheet has been loaded }; stylesheet.onerror = () => { console.log("An error occurred loading the stylesheet!"); }; </script> <link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet" /> ``` > **Note:** The `load` event fires once the stylesheet and all of its imported content has been loaded and parsed, and immediately before the styles start being applied to the content. ### Preload examples You can find a number of `<link rel="preload">` examples in [Preloading content with `rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload). ### Blocking rendering till a resource is fetched You can include `render` token inside a `blocking` attribute; the rendering of the page will be blocked till the resource is fetched. For example: ```html <link blocking="render" rel="preload" href="critical-font.woff2" as="font" crossorigin /> ``` ## Technical summary <table class="properties"> <tbody> <tr> <th> <a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a> </th> <td> Metadata content. If <code><a href="/en-US/docs/Web/HTML/Global_attributes/itemprop">itemprop</a></code> is present: <a href="/en-US/docs/Web/HTML/Content_categories#flow_content">Flow content</a> and <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> Any element that accepts metadata elements. If <a href="/en-US/docs/Web/HTML/Global_attributes/itemprop">itemprop</a> is present: 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="/en-US/docs/Web/Accessibility/ARIA/Roles/link_role"><code>link</code></a> with <code>href</code> attribute</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("HTMLLinkElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTTPHeader("Link")}} HTTP header - [The `integrity` attribute](https://150daysofhtml.com/book/day010/) on 150daysofhtml.com (2021)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/menu/index.md
--- title: "<menu>: The Menu element" slug: Web/HTML/Element/menu page-type: html-element browser-compat: html.elements.menu --- {{HTMLSidebar}} The **`<menu>`** [HTML](/en-US/docs/Web/HTML) element is described in the HTML specification as a semantic alternative to {{HTMLElement("ul")}}, but treated by browsers (and exposed through the accessibility tree) as no different than {{HTMLElement("ul")}}. It represents an unordered list of items (which are represented by {{HTMLElement("li")}} elements). {{EmbedInteractiveExample("pages/tabbed/menu.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<menu>` and {{HTMLElement("ul")}} elements both represent an unordered list of items. The key difference is that {{HTMLElement("ul")}} primarily contains items for display, while `<menu>` was intended for interactive items. The related {{HTMLElement("menuitem")}} element has been deprecated. > **Note:** In early versions of the HTML specification, the `<menu>` element had an additional use case as a context menu. This functionality is considered obsolete and is not in the specification. ## Examples ### Toolbar In this example, a `<menu>` is used to create a toolbar for an editing application. #### HTML ```html <menu> <li><button onclick="copy()">Copy</button></li> <li><button onclick="cut()">Cut</button></li> <li><button onclick="paste()">Paste</button></li> </menu> ``` Note that this is functionally no different from: ```html <ul> <li><button onclick="copy()">Copy</button></li> <li><button onclick="cut()">Cut</button></li> <li><button onclick="paste()">Paste</button></li> </ul> ``` #### CSS ```css menu, ul { display: flex; list-style: none; padding: 0; width: 400px; } li { flex-grow: 1; } button { width: 100%; } ``` #### Result {{EmbedLiveSample("Toolbar", "100%", 100)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <p> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. If the element's children include at least one {{HTMLElement("li")}} element: <a href="/en-US/docs/Web/HTML/Content_categories#palpable_content" >Palpable content</a >. </p> </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <p> Zero or more occurrences of {{HTMLElement("li")}}, {{HTMLElement("script")}}, and {{HTMLElement("template")}}. </p> </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#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/List_role" >list</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/directory_role"><code>directory</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></a>, <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role" >listbox</a ></code >, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menu_role"><code>menu</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menubar_role"><code>menubar</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radiogroup_role"><code>radiogroup</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tablist_role"><code>tablist</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/toolbar_role"><code>toolbar</code></a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tree_role"><code>tree</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLMenuElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other list-related HTML Elements: {{HTMLElement("ol")}}, {{HTMLElement("ul")}}, and {{HTMLElement("li")}}.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/span/index.md
--- title: "<span>: The Content Span element" slug: Web/HTML/Element/span page-type: html-element browser-compat: html.elements.span --- {{HTMLSidebar}} The **`<span>`** [HTML](/en-US/docs/Web/HTML) element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the [`class`](/en-US/docs/Web/HTML/Global_attributes#class) or [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attributes), or because they share attribute values, such as [`lang`](/en-US/docs/Web/HTML/Global_attributes#lang). It should be used only when no other semantic element is appropriate. `<span>` is very much like a {{HTMLElement("div")}} element, but {{HTMLElement("div")}} is a [block-level element](/en-US/docs/Glossary/Block-level_content) whereas a `<span>` is an [inline-level element](/en-US/docs/Glossary/Inline-level_content). {{EmbedInteractiveExample("pages/tabbed/span.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Example ### Example 1 #### HTML ```html <p><span>Some text</span></p> ``` #### Result {{EmbedLiveSample('Example_1')}} ### Example 2 #### HTML ```html <li> <span> <a href="portfolio.html" target="_blank">See my portfolio</a> </span> </li> ``` #### CSS ```css li span { background: gold; } ``` #### Result {{EmbedLiveSample('Example_2')}} ## 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#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 >, 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> <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("HTMLSpanElement")}} </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML {{HTMLElement("div")}} element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/picture/index.md
--- title: "<picture>: The Picture element" slug: Web/HTML/Element/picture page-type: html-element browser-compat: html.elements.picture --- {{HTMLSidebar}} The **`<picture>`** [HTML](/en-US/docs/Web/HTML) element contains zero or more {{HTMLElement("source")}} elements and one {{HTMLElement("img")}} element to offer alternative versions of an image for different display/device scenarios. The browser will consider each child `<source>` element and choose the best match among them. If no matches are found—or the browser doesn't support the `<picture>` element—the URL of the `<img>` element's [`src`](/en-US/docs/Web/HTML/Element/img#src) attribute is selected. The selected image is then presented in the space occupied by the `<img>` element. {{EmbedInteractiveExample("pages/tabbed/picture.html", "tabbed-standard")}} To decide which URL to load, the {{Glossary("user agent")}} examines each `<source>`'s [`srcset`](/en-US/docs/Web/HTML/Element/source#srcset), [`media`](/en-US/docs/Web/HTML/Element/source#media), and [`type`](/en-US/docs/Web/HTML/Element/source#type) attributes to select a compatible image that best matches the current layout and capabilities of the display device. The `<img>` element serves two purposes: 1. It describes the size and other attributes of the image and its presentation. 2. It provides a fallback in case none of the offered `<source>` elements are able to provide a usable image. Common use cases for `<picture>`: - **Art direction.** Cropping or modifying images for different `media` conditions (for example, loading a simpler version of an image which has too many details, on smaller displays). - **Offering alternative image formats**, for cases where certain formats are not supported. > **Note:** For example, newer formats like [AVIF](/en-US/docs/Web/Media/Formats/Image_types#avif_image) or [WEBP](/en-US/docs/Web/Media/Formats/Image_types#webp_image) have many advantages, but might not be supported by the browser. A list of supported image formats can be found in: [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types). - **Saving bandwidth and speeding page load times** by loading the most appropriate image for the viewer's display. If providing higher-density versions of an image for high-DPI (Retina) display, use [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) on the `<img>` element instead. This lets browsers opt for lower-density versions in data-saving modes, and you don't have to write explicit `media` conditions. ## Attributes This element includes only [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes You can use the {{cssxref("object-position")}} property to adjust the positioning of the image within the element's frame, and the {{cssxref("object-fit")}} property to control how the image is resized to fit within the frame. > **Note:** Use these properties on the child `<img>` element, **not** the `<picture>` element. ## Examples These examples demonstrate how different attributes of the {{HTMLElement("source")}} element change the selection of the image inside `<picture>`. ### The media attribute The `media` attribute specifies a media condition (similar to a media query) that the user agent will evaluate for each {{HTMLElement("source")}} element. If the {{HTMLElement("source")}}'s media condition evaluates to `false`, the browser skips it and evaluates the next element inside `<picture>`. ```html <picture> <source srcset="mdn-logo-wide.png" media="(min-width: 600px)" /> <img src="mdn-logo-narrow.png" alt="MDN" /> </picture> ``` ### The srcset attribute The [srcset](/en-US/docs/Web/HTML/Element/source#srcset) attribute is used to offer a list of possible images based on size or the display's pixel density. It is composed of a comma-separated list of image descriptors. Each image descriptor is composed of a URL of the image, and _either_: - a _width descriptor_, followed by a `w` (such as `300w`); _OR_ - a _pixel density descriptor_, followed by an `x` (such as `2x`) to serve a high-res image for high-DPI screens. Make sure to note that: - width and pixel density descriptors should not be used together - a missing pixel density descriptor implies 1x - duplicate descriptor values are not allowed (2x & 2x, 100w & 100w) The following example illustrates the usage of `srcset` attribute with the `<source>` element to specify a high-density and standard-resolution image: ```html <picture> <source srcset="logo.png, logo-1.5x.png 1.5x" /> <img src="logo.png" alt="MDN Web Docs logo" height="320" width="320" /> </picture> ``` The `srcset` attribute can also be used on the `<img>` element without needing the `<picture>` element. The following example demonstrates how to use the `srcset` attribute to specify standard-resolution and high-density images, respectively: ```html <img srcset="logo.png, logo-2x.png 2x" src="logo.png" height="320" width="320" alt="MDN Web Docs logo" /> ``` The `sizes` attribute is not mandatory when using srcset, but it is recommended to use it in order to provide additional information to the browser to help it select the best image source. Without sizes, the browser will use the default size of the image as specified by its dimensions in pixels. This may not be the best fit for all devices, especially if the image is displayed on different screen sizes or in different contexts. Please note that sizes will have its effect only if width dimension descriptors are provided with srcset instead of pixel ratio values (200w instead of 2x for example). For more information on using `srcset`, see the [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) documentation. ### The type attribute The `type` attribute specifies a [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) for the resource URL(s) in the {{HTMLElement("source")}} element's `srcset` attribute. If the user agent does not support the given type, the {{HTMLElement("source")}} element is skipped. ```html <picture> <source srcset="photo.avif" type="image/avif" /> <source srcset="photo.webp" type="image/webp" /> <img src="photo.jpg" alt="photo" /> </picture> ``` ## 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 >, phrasing content, embedded content </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Zero or more {{HTMLElement("source")}} elements, followed by one {{HTMLElement("img")}} element, optionally intermixed with script-supporting elements. </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 allows embedded content.</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("HTMLPictureElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("img")}} element - {{HTMLElement("source")}} element - Positioning and sizing the picture within its frame: {{cssxref("object-position")}} and {{cssxref("object-fit")}} - [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/nobr/index.md
--- title: "<nobr>: The Non-Breaking Text element" slug: Web/HTML/Element/nobr page-type: html-element status: - deprecated browser-compat: html.elements.nobr --- {{HTMLSidebar}}{{deprecated_header}} The **`<nobr>`** [HTML](/en-US/docs/Web/HTML) element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text. > **Warning:** Although this element is widely supported, it was _never_ standard HTML, so you shouldn't use it. Instead, use the CSS property {{CSSxRef("white-space")}} like this: ```html <span style="white-space: nowrap;">Long line with no breaks</span> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{CSSxRef("white-space")}} - {{CSSxRef("overflow")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/optgroup/index.md
--- title: "<optgroup>: The Option Group element" slug: Web/HTML/Element/optgroup page-type: html-element browser-compat: html.elements.optgroup --- {{HTMLSidebar}} The **`<optgroup>`** [HTML](/en-US/docs/Web/HTML) element creates a grouping of options within a {{HTMLElement("select")}} element. {{EmbedInteractiveExample("pages/tabbed/optgroup.html", "tabbed-standard")}} > **Note:** Optgroup elements may not be nested. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `disabled` - : If this Boolean attribute is set, none of the items in this option group is selectable. Often browsers grey out such control and it won't receive any browsing events, like mouse clicks or focus-related ones. - `label` - : The name of the group of options, which the browser can use when labeling the options in the user interface. This attribute is mandatory if this element is used. ## Examples ```html <select> <optgroup label="Group 1"> <option>Option 1.1</option> </optgroup> <optgroup label="Group 2"> <option>Option 2.1</option> <option>Option 2.2</option> </optgroup> <optgroup label="Group 3" disabled> <option>Option 3.1</option> <option>Option 3.2</option> <option>Option 3.3</option> </optgroup> </select> ``` ### Result {{EmbedLiveSample("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>Zero or more {{HTMLElement("option")}} elements.</td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is mandatory. The end tag is optional if this element is immediately followed by another <code>&#x3C;optgroup></code> element, or if the parent element has no more content. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td>A {{HTMLElement("select")}} element.</td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role"><code>group</code></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("HTMLOptGroupElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other form-related elements: {{HTMLElement("form")}}, {{HTMLElement("legend")}}, {{HTMLElement("label")}}, {{HTMLElement("button")}}, {{HTMLElement("select")}}, {{HTMLElement("datalist")}}, {{HTMLElement("option")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("textarea")}}, {{HTMLElement("input")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}} and {{HTMLElement("meter")}}.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/hgroup/index.md
--- title: "<hgroup>: The Heading Group element" slug: Web/HTML/Element/hgroup page-type: html-element browser-compat: html.elements.hgroup --- {{HTMLSidebar}} The **`<hgroup>`** [HTML](/en-US/docs/Web/HTML) element represents a heading and related content. It groups a single [`<h1>–<h6>`](/en-US/docs/Web/HTML/Element/Heading_Elements) element with one or more [`<p>`](/en-US/docs/Web/HTML/Element/p). {{EmbedInteractiveExample("pages/tabbed/hgroup.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<hgroup>` element allows the grouping of a heading with any secondary content, such as subheadings, an alternative title, or tagline. Each of these types of content represented as a `<p>` element within the `<hgroup>`. The `<hgroup>` itself has no impact on the document outline of a web page. Rather, the single allowed heading within the `<hgroup>` contributes to the document outline. ## Examples ```html <!doctype html> <title>HTML Standard</title> <body> <hgroup id="document-title"> <h1>HTML: Living Standard</h1> <p>Last Updated 12 July 2022</p> </hgroup> <p>Some intro to the document.</p> <h2>Table of contents</h2> <ol id="toc"> … </ol> <h2>First section</h2> <p>Some intro to the first section.</p> </body> ``` ### Result {{EmbedLiveSample('Examples')}} ## Accessibility concerns The `<hgroup>` presently has no strong accessibility semantics. The content of the element (a heading and optional paragraphs) is what is exposed by browser accessibility APIs. ## 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 >, heading content, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Zero or more {{HTMLElement("p")}} elements, followed by one {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, or {{HTMLElement("Heading_Elements", "h6")}} element, followed by zero or more {{HTMLElement("p")}} elements. </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#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 - Others section-related elements: {{HTMLElement("body")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("address")}}; - [Sections and outlines of an HTML document](/en-US/docs/Web/HTML/Element/Heading_Elements).
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/b/index.md
--- title: "<b>: The Bring Attention To element" slug: Web/HTML/Element/b page-type: html-element browser-compat: html.elements.b --- {{HTMLSidebar}} The **`<b>`** [HTML](/en-US/docs/Web/HTML) element is used to draw the reader's attention to the element's contents, which are not otherwise granted special importance. This was formerly known as the Boldface element, and most browsers still draw the text in boldface. However, you should not use `<b>` for styling text or granting importance. If you wish to create boldface text, you should use the CSS {{cssxref("font-weight")}} property. If you wish to indicate an element is of special importance, you should use the {{HTMLElement("strong")}} element. {{EmbedInteractiveExample("pages/tabbed/b.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Use the `<b>` for cases like keywords in a summary, product names in a review, or other spans of text whose typical presentation would be boldfaced (but not including any special importance). - Do not confuse the `<b>` element with the {{HTMLElement("strong")}}, {{HTMLElement("em")}}, or {{HTMLElement("mark")}} elements. The {{HTMLElement("strong")}} element represents text of certain _importance_, {{HTMLElement("em")}} puts some emphasis on the text and the {{HTMLElement("mark")}} element represents text of certain _relevance_. The `<b>` element doesn't convey such special semantic information; use it only when no others fit. - Similarly, do not mark titles and headings using the `<b>` element. For this purpose, use the {{HTMLElement("Heading_Elements", "h1")}} to {{HTMLElement("Heading_Elements", "h6")}} tags. Further, stylesheets can change the default style of these elements, with the result that they are not _necessarily_ displayed in bold. - It is a good practice to use the [`class`](/en-US/docs/Web/HTML/Global_attributes#class) attribute on the `<b>` element in order to convey additional semantic information as needed (for example `<b class="lead">` for the first sentence in a paragraph). This makes it easier to manage multiple use cases of `<b>` if your stylistic needs change, without the need to change all of its uses in the HTML. - Historically, the `<b>` element was meant to make text boldface. Styling information has been deprecated since HTML4, so the meaning of the `<b>` element has been changed. - If there is no semantic purpose to using the `<b>` element, you should use the CSS {{cssxref("font-weight")}} property with the value `"bold"` instead in order to make text bold. ## Examples ```html <p> This article describes several <b class="keywords">text-level</b> elements. It explains their usage in an <b class="keywords">HTML</b> document. </p> Keywords are displayed with the default style of the <b>element, likely in bold.</b> ``` ### Result {{EmbedLiveSample("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> <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("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other elements conveying text-level semantics: {{HTMLElement("a")}}, {{HTMLElement("em")}}, {{HTMLElement("strong")}}, {{HTMLElement("small")}}, {{HTMLElement("cite")}}, {{HTMLElement("q")}}, {{HTMLElement("dfn")}}, {{HTMLElement("abbr")}}, {{HTMLElement("time")}}, {{HTMLElement("code")}}, {{HTMLElement("var")}}, {{HTMLElement("samp")}}, {{HTMLElement("kbd")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{HTMLElement("i")}}, {{HTMLElement("mark")}}, {{HTMLElement("ruby")}}, {{HTMLElement("rp")}}, {{HTMLElement("rt")}}, {{HTMLElement("bdo")}}, {{HTMLElement("span")}}, {{HTMLElement("br")}}, {{HTMLElement("wbr")}}. - [Using \<b> and \<i> elements (W3C)](https://www.w3.org/International/questions/qa-b-and-i-tags)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/datalist/index.md
--- title: "<datalist>: The HTML Data List element" slug: Web/HTML/Element/datalist page-type: html-element browser-compat: html.elements.datalist --- {{HTMLSidebar}} The **`<datalist>`** [HTML](/en-US/docs/Web/HTML) element contains a set of {{HTMLElement("option")}} elements that represent the permissible or recommended options available to choose from within other controls. {{EmbedInteractiveExample("pages/tabbed/datalist.html", "tabbed-standard")}} To bind the `<datalist>` element to the control, we give it a unique identifier in the [`id`](/en-US/docs/Web/HTML/Global_attributes/id) attribute, and then add the [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute to the {{HTMLElement("input")}} element with the same identifier as value. Only certain types of {{HTMLElement("input")}} support this behavior, and it can also vary from browser to browser. > **Note:** The `<option>` element can store a value as internal content and in the `value` and `label` attributes. Which one will be visible in the drop-down menu depends on the browser, but when clicked, content entered into control field will always come from the `value` attribute. ## Attributes This element has no other attributes than the [global attributes](/en-US/docs/Web/HTML/Global_attributes), common to all elements. ## Examples ### Textual types Recommended values in types {{HTMLElement("input/text", "text")}}, {{HTMLElement("input/search", "search")}}, {{HTMLElement("input/url", "url")}}, {{HTMLElement("input/tel", "tel")}}, {{HTMLElement("input/email", "email")}} and {{HTMLElement("input/number", "number")}}, are displayed in a drop-down menu when user clicks or double-clicks on the control. Typically the right side of a control will also have an arrow pointing to the presence of predefined values. ```html <label for="myBrowser">Choose a browser from this list:</label> <input list="browsers" id="myBrowser" name="myBrowser" /> <datalist id="browsers"> <option value="Chrome"></option> <option value="Firefox"></option> <option value="Opera"></option> <option value="Safari"></option> <option value="Microsoft Edge"></option> </datalist> ``` {{EmbedLiveSample("Textual_types", 600, 40)}} ### Date and Time types The types {{HTMLElement("input/month", "month")}}, {{HTMLElement("input/week", "week")}}, {{HTMLElement("input/date", "date")}}, {{HTMLElement("input/time", "time")}} and {{HTMLElement("input/datetime-local", "datetime-local")}} can show an interface that allows a convenient selection of a date and time. Predefined values can be shown there, allowing the user to quickly fill the control value. > **Note:** When type is not supported, `text` type creating simple text field will be used instead. That field will correctly recognize recommended values and display them to the user in a drop-down menu. ```html <input type="time" list="popularHours" /> <datalist id="popularHours"> <option value="12:00"></option> <option value="13:00"></option> <option value="14:00"></option> </datalist> ``` {{EmbedLiveSample("Date_and_Time_types", 600, 40)}} ### Range type The recommended values in the {{HTMLElement("input/range", "range")}} type will be shown as series of hash marks that the user can easily select. ```html <label for="tick">Tip amount:</label> <input type="range" list="tickmarks" min="0" max="100" id="tick" name="tick" /> <datalist id="tickmarks"> <option value="0"></option> <option value="10"></option> <option value="20"></option> <option value="30"></option> </datalist> ``` {{EmbedLiveSample("Range_type", 600, 70)}} ### Color type The {{HTMLElement("input/color", "color")}} type can show predefined colors in a browser-provided interface. ```html <label for="colors">Pick a color (preferably a red tone):</label> <input type="color" list="redColors" id="colors" /> <datalist id="redColors"> <option value="#800000"></option> <option value="#8B0000"></option> <option value="#A52A2A"></option> <option value="#DC143C"></option> </datalist> ``` {{EmbedLiveSample("Color_type", 600, 70)}} ### Password type The specification allows linking `<datalist>` with a {{HTMLElement("input/password", "password")}} type, but no browser supports it for security reasons. ```html <label for="pwd">Enter a password:</label> <input type="password" list="randomPassword" id="pwd" /> <datalist id="randomPassword"> <option value="5Mg[_3DnkgSu@!q#"></option> </datalist> ``` {{EmbedLiveSample("Password_type", 600, 40)}} ## Accessibility concerns When deciding to use the `<datalist>` element, here are some accessibility issues to be mindful of: - The font size of the data list's options does not zoom, always remaining the same size. The contents of the autosuggest do not grow or shrink when the rest of the contents are zoomed in or out. - As targeting the list of options with CSS is very limited to non-existent, rendering can not be styled for high-contrast mode. - Some screen reader/browser combinations, including NVDA and Firefox, do not announce the contents of the autosuggest popup. ## 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> Either <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a > or zero or more {{HTMLElement("option")}} elements. </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="/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role" >listbox</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("HTMLDataListElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("input")}} element, and more specifically its [`list`](/en-US/docs/Web/HTML/Element/input#list) attribute; - The {{HTMLElement("option")}} element.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/image/index.md
--- title: "<image>: The Image element" slug: Web/HTML/Element/image page-type: html-element status: - deprecated - non-standard browser-compat: html.elements.image --- {{HTMLSidebar}}{{deprecated_header}}{{Non-standard_header}} The **`<image>`** [HTML](/en-US/docs/Web/HTML) element is an ancient and poorly supported precursor to the {{HTMLElement("img")}} element. **It should not be used**. Some browsers will attempt to automatically convert this into an {{HTMLElement("img")}} element, and may succeed if the [`src`](/en-US/docs/Web/HTML/Element/img#src) attribute is specified as well. <!-- ## Technical summary --> ## Specifications This does not appear to have been part of any formal specification. It was mentioned in [HTML+ Discussion Document - Dave Raggett, November 8, 1993](https://www.w3.org/MarkUp/HTMLPlus/htmlplus_21.html) (Section 5.9 - Images), but was not part of the first revision of [HyperText Markup Language Specification - 2.0](https://datatracker.ietf.org/doc/html/draft-ietf-html-spec-00) in 1994. ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("img")}}: The correct way to display an image in a document - {{HTMLElement("picture")}}: A more powerful correct way to display an image in a document
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/summary/index.md
--- title: "<summary>: The Disclosure Summary element" slug: Web/HTML/Element/summary page-type: html-element browser-compat: html.elements.summary --- {{HTMLSidebar}} The **`<summary>`** [HTML](/en-US/docs/Web/HTML) element specifies a summary, caption, or legend for a {{HTMLElement("details")}} element's disclosure box. Clicking the `<summary>` element toggles the state of the parent `<details>` element open and closed. {{EmbedInteractiveExample("pages/tabbed/summary.html","tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<summary>` element's contents can be any heading content, plain text, or HTML that can be used within a paragraph. A `<summary>` element may _only_ be used as the first child of a `<details>` element. When the user clicks on the summary, the parent `<details>` element is toggled open or closed, and then a {{domxref("HTMLDetailsElement/toggle_event", "toggle")}} event is sent to the `<details>` element, which can be used to let you know when this state change occurs. The content of the `<details>` provides the {{glossary("accessible description")}} for the `<summary>`. ### Default label text If a `<details>` element's first child is not a `<summary>` element, the {{Glossary("user agent")}} will use a default string (typically "Details") as the label for the disclosure box. ### Default style Per the HTML specification, the default style for `<summary>` elements includes `display: list-item`. This makes it possible to change or remove the icon displayed as the disclosure widget next to the label from the default, which is typically a triangle. You can also change the style to `display: block` to remove the disclosure triangle. See the [Browser compatibility](#browser_compatibility) section for details, as not all browsers support full functionality of this element yet. For Webkit-based browsers, such as Safari, it is possible to control the icon display through the non-standard CSS pseudo-element `::-webkit-details-marker`. To remove the disclosure triangle, use `summary::-webkit-details-marker { display: none }`. ## Examples Below are some examples showing `<summary>` in use. You can find more examples in the documentation for the {{HTMLElement("details")}} element. ### Basic example A simple example showing the use of `<summary>` in a {{HTMLElement("details")}} element: ```html <details open> <summary>Overview</summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> ``` #### Result {{EmbedLiveSample("Basic_example", 650, 120)}} ### Summaries as headings You can use heading elements in `<summary>`, like this: ```html <details open> <summary><h4>Overview</h4></summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> ``` #### Result {{EmbedLiveSample("Summaries_as_headings", 650, 120)}} This currently has some spacing issues that could be addressed using CSS. > **Warning:** Because the `<summary>` element has a default role of [button](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role) (which strips all roles from child elements), this example will not work for users of assistive technologies such as screen readers. The `<h4>` will have its role removed and thus will not be treated as a heading for these users. ### HTML in summaries This example adds some semantics to the `<summary>` element to indicate the label as important: ```html <details open> <summary><strong>Overview</strong></summary> <ol> <li>Cash on hand: $500.00</li> <li>Current invoice: $75.30</li> <li>Due date: 5/6/19</li> </ol> </details> ``` #### Result {{EmbedLiveSample("HTML_in_summaries", 650, 120)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a > or one element of <a href="/en-US/docs/Web/HTML/Content_categories#heading_content" >Heading content</a > </td> </tr> <tr> <th scope="row">Tag omission</th> <td>None; both the start tag and the end tag are mandatory.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td>The {{HTMLElement("details")}} 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("details")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/dfn/index.md
--- title: "<dfn>: The Definition element" slug: Web/HTML/Element/dfn page-type: html-element browser-compat: html.elements.dfn --- {{HTMLSidebar}} The **`<dfn>`** [HTML](/en-US/docs/Web/HTML) element indicates a term to be defined. The `<dfn>` element should be used in a complete definition statement, where the ancestor {{HTMLElement("p")}} element, the {{HTMLElement("dt")}}/{{HTMLElement("dd")}} pairing, or the nearest {{HTMLElement("section")}} ancestor of the `<dfn>` element, is considered to be the full definition of the term. {{EmbedInteractiveExample("pages/tabbed/dfn.html", "tabbed-shorter")}} ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). The [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute has special meaning, as noted below. ## Usage notes There are some not-entirely-obvious aspects to using the `<dfn>` element. We examine those here. ### Specifying the term being defined The term being defined is identified following these rules: 1. If the `<dfn>` element has a [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute, the value of the `title` attribute is considered to be the term being defined. The element must still have text within it, but that text may be an abbreviation (perhaps using {{HTMLElement("abbr")}}) or another form of the term. 2. If the `<dfn>` contains a single child element and does not have any text content of its own, and the child element is an {{HTMLElement("abbr")}} element with a `title` attribute itself, then the exact value of the `<abbr>` element's `title` is the term being defined. 3. Otherwise, the text content of the `<dfn>` element is the term being defined. This is shown [in the first example below](#basic_identification_of_a_term). > **Note:** If the `<dfn>` element has a `title` attribute, it _must_ contain the term being defined and no other text. ### Links to `<dfn>` elements If you include an [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute on the `<dfn>` element, you can then link to it using {{HTMLElement("a")}} elements. Such links should be uses of the term, with the intent being that the reader can quickly navigate to the term's definition if they're not already aware of it, by clicking on the term's link. This is shown in the example under [Links to definitions](#links_to_definitions) below. ## Examples Let's take a look at some examples of various usage scenarios. ### Basic identification of a term This example uses a plain `<dfn>` element to identify the location of a term within the definition. #### HTML ```html <p> The <strong>HTML Definition element (<dfn>&lt;dfn&gt;</dfn>)</strong> is used to indicate the term being defined within the context of a definition phrase or sentence. </p> ``` Since the `<dfn>` element has no `title`, the text contents of the `<dfn>` element itself are used as the term being defined. #### Result {{EmbedLiveSample("Basic_identification_of_a_term", 650, 120)}} ### Links to definitions To add links to the definitions, you create the link the same way you always do, with the {{HTMLElement("a")}} element. #### HTML ```html-nolint <p> The <strong>HTML Definition element (<dfn id="definition-dfn">&lt;dfn&gt;</dfn>)</strong> is used to indicate the term being defined within the context of a definition phrase or sentence. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Graece donan, Latine voluptatem vocant. Confecta res esset. Duo Reges: constructio interrete. Scrupulum, inquam, abeunti; </p> <p> Because of all of that, we decided to use the <code><a href="#definition-dfn">&lt;dfn&gt;</a></code> element for this project. </p> ``` Here we see the definition — now with an [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute, `"definition-dfn"`, which can be used as the target of a link. Later on, a link is created using `<a>` with the [`href`](/en-US/docs/Web/HTML/Element/a#href) attribute set to `"#definition-dfn"` to set up the link back to the definition. #### Result {{EmbedLiveSample("Links_to_definitions", 650, 300)}} ### Using abbreviations and definitions together In some cases, you may wish to use an abbreviation for a term when defining it. This can be done by using the `<dfn>` and {{HTMLElement("abbr")}} elements in tandem, like this: #### HTML ```html <p> The <dfn><abbr title="Hubble Space Telescope">HST</abbr></dfn> is among the most productive scientific instruments ever constructed. It has been in orbit for over 20 years, scanning the sky and returning data and photographs of unprecedented quality and detail. </p> <p> Indeed, the <abbr title="Hubble Space Telescope">HST</abbr> has arguably done more to advance science than any device ever built. </p> ``` Note the `<abbr>` element nested inside the `<dfn>`. The former establishes that the term is an abbreviation ("HST") and specifies the full term ("Hubble Space Telescope") in its `title` attribute. The latter indicates that the abbreviated term represents a term being defined. #### Result {{EmbedLiveSample("Using_abbreviations_and_definitions_together", 650, 200)}} ## 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>, but no {{HTMLElement("dfn")}} element must be a descendant. </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="/en-US/docs/Web/Accessibility/ARIA/Roles/term_role"><code>term</code></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 - Elements related to definition lists: {{HTMLElement("dl")}}, {{HTMLElement("dt")}}, {{HTMLElement("dd")}} - {{HTMLElement("abbr")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/font/index.md
--- title: <font> slug: Web/HTML/Element/font page-type: html-element status: - deprecated browser-compat: html.elements.font --- {{HTMLSidebar}}{{Deprecated_Header}} The **`<font>`** [HTML](/en-US/docs/Web/HTML) element defines the font size, color and face for its content. > **Warning:** Do not use this element. Use the CSS [Fonts](/en-US/docs/Web/CSS/CSS_fonts) properties to style text. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `color` {{Deprecated_Inline}} - : This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. - `face` {{Deprecated_Inline}} - : This attribute contains a comma-separated list of one or more font names. The document text in the default style is rendered in the first font face that the client's browser supports. If no font listed is installed on the local system, the browser typically defaults to the proportional or fixed-width font for that system. - `size` {{Deprecated_Inline}} - : This attribute specifies the font size as either a numeric or relative value. Numeric values range from `1` to `7` with `1` being the smallest and `3` the default. It can be defined using a relative value, like `+2` or `-3`, which sets it relative to `3`, the default value. ## DOM interface This element implements the {{domxref("HTMLFontElement")}} interface. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/video/index.md
--- title: "<video>: The Video Embed element" slug: Web/HTML/Element/video page-type: html-element browser-compat: html.elements.video --- {{HTMLSidebar}} The **`<video>`** [HTML](/en-US/docs/Web/HTML) element embeds a media player which supports video playback into the document. You can use `<video>` for audio content as well, but the {{HTMLElement("audio")}} element may provide a more appropriate user experience. {{EmbedInteractiveExample("pages/tabbed/video.html", "tabbed-standard")}} The above example shows simple usage of the `<video>` element. In a similar manner to the {{htmlelement("img")}} element, we include a path to the media we want to display inside the `src` attribute; we can include other attributes to specify information such as video width and height, whether we want it to autoplay and loop, whether we want to show the browser's default video controls, etc. The content inside the opening and closing `<video></video>` tags is shown as a fallback in browsers that don't support the element. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `autoplay` - : A Boolean attribute; if specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data. > **Note:** Sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, this can be useful when creating media elements whose source will be set at a later time, under user control. See our [autoplay guide](/en-US/docs/Web/Media/Autoplay_guide) for additional information about how to properly use autoplay. To disable video autoplay, `autoplay="false"` will not work; the video will autoplay if the attribute is there in the `<video>` tag at all. To remove autoplay, the attribute needs to be removed altogether. In some browsers (e.g. Chrome 70.0) autoplay doesn't work if no `muted` attribute is present. - `controls` - : If this attribute is present, the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback. - `controlslist` - : The [`controlslist`](https://wicg.github.io/controls-list/explainer.html) attribute, when specified, helps the browser select what controls to show for the `video` element whenever the browser shows its own set of controls (that is, when the `controls` attribute is specified). The allowed values are `nodownload`, `nofullscreen` and `noremoteplayback`. Use the [`disablepictureinpicture`](#disablepictureinpicture) attribute if you want to disable the Picture-In-Picture mode (and the control). - `crossorigin` - : This [enumerated](/en-US/docs/Glossary/Enumerated) attribute indicates whether to use CORS to fetch the related video. [CORS-enabled resources](/en-US/docs/Web/HTML/CORS_enabled_image) can be reused in the {{HTMLElement("canvas")}} element without being _tainted_. The allowed values are: - `anonymous` - : Sends a cross-origin request without a credential. In other words, it sends the `Origin:` HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the `Access-Control-Allow-Origin:` HTTP header), the resource will be _tainted_, and its usage restricted. - `use-credentials` - : Sends a cross-origin request with a credential. In other words, it sends the `Origin:` HTTP header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through `Access-Control-Allow-Credentials:` HTTP header), the resource will be _tainted_ and its usage restricted. When not present, the resource is fetched without a CORS request (i.e. without sending the `Origin:` HTTP header), preventing its non-tainted use in {{HTMLElement('canvas')}} elements. If invalid, it is handled as if the enumerated keyword `anonymous` was used. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for additional information. - `disablepictureinpicture` - : Prevents the browser from suggesting a Picture-in-Picture context menu or to request Picture-in-Picture automatically in some cases. - `disableremoteplayback` - : A Boolean attribute used to disable the capability of remote playback in devices that are attached using wired (HDMI, DVI, etc.) and wireless technologies (Miracast, Chromecast, DLNA, AirPlay, etc.). In Safari, you can use [`x-webkit-airplay="deny"`](https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/AirPlayGuide/OptingInorOutofAirPlay/OptingInorOutofAirPlay.html) as a fallback. - `height` - : The height of the video's display area, 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)). - `loop` - : A Boolean attribute; if specified, the browser will automatically seek back to the start upon reaching the end of the video. - `muted` - : A Boolean attribute that indicates the default setting of the audio contained in the video. If set, the audio will be initially silenced. Its default value is `false`, meaning that the audio will be played when the video is played. - `playsinline` - : 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. - `poster` - : A URL for an image to be shown while the video is downloading. If this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame. - `preload` - : This enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience regarding what content is loaded before the video is played. It may have one of the following values: - `none`: Indicates that the video should not be preloaded. - `metadata`: Indicates that only video metadata (e.g. length) is fetched. - `auto`: Indicates that the whole video file can be downloaded, even if the user is not expected to use it. - _empty string_: Synonym of the `auto` value. The default value is different for each browser. The spec advises it to be set to `metadata`. > **Note:** > > - The `autoplay` attribute has precedence over `preload`. If `autoplay` is specified, the browser would obviously need to start downloading the video for playback. > - The specification does not force the browser to follow the value of this attribute; it is a mere hint. - `src` - : The URL of the video to embed. This is optional; you may instead use the {{HTMLElement("source")}} element within the video block to specify the video to embed. - `width` - : The width of the video's display area, 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)). ## Events <table class="no-markdown"> <thead> <tr> <th scope="col">Event Name</th> <th scope="col">Fired When</th> </tr> </thead> <tbody> <tr> <td> {{domxref("ScriptProcessorNode.audioprocess_event","audioprocess")}} {{Deprecated_Inline}} </td> <td> The input buffer of a {{DOMxRef("ScriptProcessorNode")}} is ready to be processed. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.canplay_event", 'canplay')}} </td> <td> The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.canplaythrough_event", 'canplaythrough')}} </td> <td> The browser estimates it can play the media up to its end without stopping for content buffering. </td> </tr> <tr> <td> {{domxref("OfflineAudioContext.complete_event", "complete")}} </td> <td> The rendering of an {{DOMxRef("OfflineAudioContext")}} is terminated. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.durationchange_event", 'durationchange')}} </td> <td>The <code>duration</code> attribute has been updated.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.emptied_event", 'emptied')}} </td> <td> The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <a href="/en-US/docs/Web/API/HTMLMediaElement/load" rel="internal" ><code>load()</code></a > method is called to reload it. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.ended_event", 'ended')}} </td> <td>Playback has stopped because the end of the media was reached.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.error_event", 'error')}} </td> <td> An error occurred while fetching the media data, or the type of the resource is not a supported media format. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.loadeddata_event", 'loadeddata')}} </td> <td>The first frame of the media has finished loading.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.loadedmetadata_event", 'loadedmetadata')}} </td> <td>The metadata has been loaded.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.loadstart_event", 'loadstart')}} </td> <td>Fired when the browser has started to load the resource.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.pause_event", 'pause')}} </td> <td>Playback has been paused.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.play_event", 'play')}} </td> <td>Playback has begun.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.playing_event", 'playing ')}} </td> <td> Playback is ready to start after having been paused or delayed due to lack of data. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.progress_event", 'progress')}} </td> <td>Fired periodically as the browser loads a resource.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.ratechange_event", 'ratechange')}} </td> <td>The playback rate has changed.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.seeked_event", 'seeked')}} </td> <td>A <em>seek</em> operation completed.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.seeking_event", 'seeking')}} </td> <td>A <em>seek</em> operation began.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.stalled_event", 'stalled')}} </td> <td> The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.suspend_event", 'suspend')}} </td> <td>Media data loading has been suspended.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.timeupdate_event", 'timeupdate')}} </td> <td> The time indicated by the <code>currentTime</code> attribute has been updated. </td> </tr> <tr> <td> {{domxref("HTMLMediaElement.volumechange_event", 'volumechange')}} </td> <td>The volume has changed.</td> </tr> <tr> <td> {{domxref("HTMLMediaElement.waiting_event", 'waiting')}} </td> <td>Playback has stopped because of a temporary lack of data.</td> </tr> </tbody> </table> ## Usage notes Browsers don't all support the same video formats; you can provide multiple sources inside nested {{htmlelement("source")}} elements, and the browser will then use the first one it understands. ```html <video controls> <source src="myVideo.webm" type="video/webm" /> <source src="myVideo.mp4" type="video/mp4" /> <p> Your browser doesn't support HTML video. Here is a <a href="myVideo.mp4" download="myVideo.mp4">link to the video</a> instead. </p> </video> ``` We offer a substantive and thorough [guide to media file types](/en-US/docs/Web/Media/Formats) and the [guide to the codecs supported for video](/en-US/docs/Web/Media/Formats/Video_codecs). Also available is a guide to [audio codecs that can be used with them](/en-US/docs/Web/Media/Formats/Audio_codecs). Other usage notes: - If you don't specify the `controls` attribute, the video won't include the browser's default controls; you can create your own custom controls using JavaScript and the {{domxref("HTMLMediaElement")}} API. See [Creating a cross-browser video player](/en-US/docs/Web/Media/Audio_and_video_delivery/cross_browser_video_player) for more details. - To allow precise control over your video (and audio) content, `HTMLMediaElement`s fire many different [events](/en-US/docs/Web/API/HTMLMediaElement#events). In addition to providing controllability, these events let you monitor the progress of both download and playback of the media, as well as the playback state and position. - You can use the {{cssxref("object-position")}} property to adjust the positioning of the video within the element's frame, and the {{cssxref("object-fit")}} property to control how the video's size is adjusted to fit within the frame. - To show subtitles/captions along with your video, you can use some JavaScript along with the {{htmlelement("track")}} element and the [WebVTT](/en-US/docs/Web/API/WebVTT_API) format. See [Adding captions and subtitles to HTML video](/en-US/docs/Web/Media/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video) for more information. - You can play audio files using a `<video>` element. This can be useful if, for example, you need to perform audio with a [WebVTT](/en-US/docs/Web/API/WebVTT_API) transcript, since the {{HTMLElement("audio")}} element doesn't allow captions using WebVTT. - To test the fallback content on browsers that support the element, you can replace `<video>` with a non-existing element like `<notavideo>`. A good general source of information on using HTML `<video>` is the [Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) beginner's tutorial. ### Styling with CSS The `<video>` element is a replaced element — its {{cssxref("display")}} value is `inline` by default, but its default width and height in the viewport is defined by the video being embedded. There are no special considerations for styling `<video>`; a common strategy is to give it a `display` value of `block` to make it easier to position, size, etc., and then provide styling and layout information as required. [Video player styling basics](/en-US/docs/Web/Media/Audio_and_video_delivery/Video_player_styling_basics) provides some useful styling techniques. ### Detecting track addition and removal You can detect when tracks are added to and removed from a `<video>` element using the {{domxref("VideoTrackList/addtrack_event", "addtrack")}} and {{domxref("VideoTrackList/removetrack_event", "removetrack")}} events. However, these events aren't sent directly to the `<video>` element itself. Instead, they're sent to the track list object within the `<video>` element's {{domxref("HTMLMediaElement")}} that corresponds to the type of track that was added to the element: - {{domxref("HTMLMediaElement.audioTracks")}} - : An {{domxref("AudioTrackList")}} containing all of the media element's audio tracks. You can add a listener for `addtrack` to this object to be alerted when new audio tracks are added to the element. - {{domxref("HTMLMediaElement.videoTracks")}} - : Add an `addtrack` listener to this {{domxref("VideoTrackList")}} object to be informed when video tracks are added to the element. - {{domxref("HTMLMediaElement.textTracks")}} - : Add an `addtrack` event listener to this {{domxref("TextTrackList")}} to be notified when new text tracks are added to the element. For example, to detect when audio tracks are added to or removed from a `<video>` element, you can use code like this: ```js const elem = document.querySelector("video"); elem.audioTracks.onaddtrack = (event) => { trackEditor.addTrack(event.track); }; elem.audioTracks.onremovetrack = (event) => { trackEditor.removeTrack(event.track); }; ``` This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. You can also use {{domxref("EventTarget.addEventListener", "addEventListener()")}} to listen for the {{domxref("VideoTrackList/addtrack_event", "addtrack")}} and {{domxref("VideoTrackList/removetrack_event", "removetrack")}} events. ### Server support for video If the MIME type for the video is not set correctly on the server, the video may not show or show a gray box containing an X (if JavaScript is enabled). If you use Apache Web Server to serve Ogg Theora videos, you can fix this problem by adding the video file type extensions to "video/ogg" MIME type. The most common video file type extensions are ".ogm", ".ogv", or ".ogg". To do this, edit the "mime.types" file in "/etc/apache" or use the `"AddType"` configuration directive in `httpd.conf`. ```plain AddType video/ogg .ogm AddType video/ogg .ogv AddType video/ogg .ogg ``` If you serve your videos as WebM, you can fix this problem for the Apache Web Server by adding the extension used by your video files (".webm" is the most common one) to the MIME type "video/webm" via the "mime.types" file in "/etc/apache" or via the "AddType" configuration directive in `httpd.conf`. ```plain AddType video/webm .webm ``` Your web host may provide an easy interface to MIME type configuration changes for new technologies until a global update naturally occurs. ## Examples ### Single source This example plays a video when activated, providing the user with the browser's default video controls to control playback. #### HTML ```html <!-- Simple video example --> <!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org --> <!-- Poster from peach.blender.org --> <video controls src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4" poster="https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217" width="620"> Sorry, your browser doesn't support embedded videos, but don't worry, you can <a href="https://archive.org/details/BigBuckBunny_124">download it</a> and watch it with your favorite video player! </video> ``` #### Result {{EmbedLiveSample('Single source', '', '400')}} Until the video starts playing, the image provided in the `poster` attribute is displayed in its place. If the browser doesn't support video playback, the fallback text is displayed. ### Multiple sources This example builds on the last one, offering three different sources for the media; this allows the video to be watched regardless of which video codecs are supported by the browser. #### HTML ```html <!-- Using multiple sources as fallbacks for a video tag --> <!-- 'Elephants Dream' by Orange Open Movie Project Studio, licensed under CC-3.0, hosted by archive.org --> <!-- Poster hosted by Wikimedia --> <video width="620" controls poster="https://upload.wikimedia.org/wikipedia/commons/e/e8/Elephants_Dream_s5_both.jpg"> <source src="https://archive.org/download/ElephantsDream/ed_hd.ogv" type="video/ogg" /> <source src="https://archive.org/download/ElephantsDream/ed_hd.avi" type="video/avi" /> <source src="https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4" type="video/mp4" /> Sorry, your browser doesn't support embedded videos, but don't worry, you can <a href="https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4" download="ed_1024_512kb.mp4"> download the MP4 </a> and watch it with your favorite video player! </video> ``` #### Result {{EmbedLiveSample('Multiple sources', '', '400')}} First [Ogg](/en-US/docs/Web/Media/Formats/Containers#ogg) is tried. If that can't be played, then AVI is tried. Finally, [MP4](/en-US/docs/Web/Media/Formats/Containers#mpeg-4_mp4) is tried. A fallback message is displayed if the video element isn't supported, but not if all sources fail. Some media file types let you provide more specific information using the [`codecs`](/en-US/docs/Web/Media/Formats/codecs_parameter) parameter as part of the file's type string. A relatively simple example is `video/webm; codecs="vp8, vorbis"`, which says that the file is a [WebM](/en-US/docs/Web/Media/Formats/Containers#webm) video using [VP8](/en-US/docs/Web/Media/Formats/Video_codecs#vp8) for its video and [Vorbis](/en-US/docs/Web/Media/Formats/Audio_codecs#vorbis) for audio. ## Accessibility concerns Videos should provide both captions and transcripts that accurately describe its content (see [Adding captions and subtitles to HTML video](/en-US/docs/Web/Media/Audio_and_video_delivery/Adding_captions_and_subtitles_to_HTML5_video) for more information on how to implement these). Captions allow people who are experiencing hearing loss to understand a video's audio content as the video is being played, while transcripts allow people who need additional time to be able to review audio content at a pace and format that is comfortable for them. It's worth noting that while you can caption audio-only media, you can only do so when playing audio in a {{HTMLElement("video")}} element, since the video region of the element is used to present the captions. This is one of the special scenarios in which it's useful to play audio in a video element. If automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source video. In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone: ```plain 14 00:03:14 --> 00:03:18 [Dramatic rock music] 15 00:03:19 --> 00:03:21 [whispering] What's that off in the distance? 16 00:03:22 --> 00:03:24 It's… it's a… 16 00:03:25 --> 00:03:32 [Loud thumping] [Dishes clattering] ``` Captions should not obstruct the main subject of the video. They can be positioned using [the `align` VTT cue setting](/en-US/docs/Web/API/WebVTT_API#cue_settings). - [Web Video Text Tracks Format (WebVTT)](/en-US/docs/Web/API/WebVTT_API) - [WebAIM: Captions, Transcripts, and Audio Descriptions](https://webaim.org/techniques/captions/) - [MDN Understanding WCAG, Guideline 1.2 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.2_—_providing_text_alternatives_for_time-based_media) - [Understanding Success Criterion 1.2.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-av-only-alt.html) - [Understanding Success Criterion 1.2.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/media-equiv-captions.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#flow_content" >Flow content</a >, phrasing content, embedded content. If it has a <a href="/en-US/docs/Web/HTML/Element/video#controls"><code>controls</code></a> attribute: interactive content and palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <p> If the element has a <a href="/en-US/docs/Web/HTML/Element/video#src"><code>src</code></a> attribute: zero or more {{HTMLElement("track")}} elements, followed by transparent content that contains no media elements–that is no {{HTMLElement("audio")}} or {{HTMLElement("video")}}. </p> <p> Else: zero or more {{HTMLElement("source")}} elements, followed by zero or more {{HTMLElement("track")}} elements, followed by transparent content that contains no media elements–that is no {{HTMLElement("audio")}} or {{HTMLElement("video")}}. </p> </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 embedded content.</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></td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLVideoElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Guide to media types and formats on the web](/en-US/docs/Web/Media/Formats) - [Media container formats (file types)](/en-US/docs/Web/Media/Formats/Containers) - [Web video codec guide](/en-US/docs/Web/Media/Formats/Video_codecs) - [Web audio codec guide](/en-US/docs/Web/Media/Formats/Audio_codecs) - Positioning and sizing the picture within its frame: {{cssxref("object-position")}} and {{cssxref("object-fit")}} - {{htmlelement("audio")}} - [Using HTML audio and video](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) - [Manipulating video using canvas](/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas) - [Configuring servers for Ogg media](/en-US/docs/Web/HTTP/Configuring_servers_for_Ogg_media)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/samp/index.md
--- title: "<samp>: The Sample Output element" slug: Web/HTML/Element/samp page-type: html-element browser-compat: html.elements.samp --- {{HTMLSidebar}} The **`<samp>`** [HTML](/en-US/docs/Web/HTML) element is used to enclose inline text which represents sample (or quoted) output from a computer program. Its contents are typically rendered using the browser's default monospaced font (such as [Courier](<https://en.wikipedia.org/wiki/Courier_(typeface)>) or Lucida Console). {{EmbedInteractiveExample("pages/tabbed/samp.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes You can use a CSS rule to override the browser's default font face for the `<samp>` element; however, it's possible that the browser's preferences may take precedence over any CSS you specify. The CSS to override the default font face would look like this: ```css samp { font-family: "Courier"; } ``` > **Note:** If you need an element which will serve as a container for output generated by your website or app's JavaScript code, you should instead use the {{HTMLElement("output")}} element. ## Examples ### Basic example In this simple example, a paragraph includes an example of the output of a program. ```html <p> When the process is complete, the utility will output the text <samp>Scan complete. Found <em>N</em> results.</samp> You can then proceed to the next step. </p> ``` #### Result {{EmbedLiveSample("Basic_example", 650, 100)}} ### Sample output including user input You can nest the {{HTMLElement("kbd")}} element within a `<samp>` block to present an example that includes text entered by the user. For example, consider this text presenting a transcript of a Linux (or macOS) console session: #### HTML ```html <pre> <samp><span class="prompt">mike@interwebz:~$</span> <kbd>md5 -s "Hello world"</kbd> MD5 ("Hello world") = 3e25960a79dbc69b674cd4ec67a72c62 <span class="prompt">mike@interwebz:~$</span> <span class="cursor">█</span></samp></pre> ``` Note the use of {{HTMLElement("span")}} to allow customization of the appearance of specific portions of the sample text such as the shell prompts and the cursor. Note also the use of `<kbd>` to represent the command the user entered at the prompt in the sample text. #### CSS The CSS that achieves the appearance we want is: ```css .prompt { color: #b00; } samp > kbd { font-weight: bold; } .cursor { color: #00b; } ``` This gives the prompt and cursor fairly subtle colorization and emboldens the keyboard input within the sample text. #### Result The resulting output is this: {{EmbedLiveSample("Sample_output_including_user_input", 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> <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 - Related elements: {{HTMLElement("kbd")}}, {{HTMLElement("code")}}, {{HTMLElement("pre")}} - The {{HTMLElement("output")}} element: a container for script-generated output
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/hr/index.md
--- title: "<hr>: The Thematic Break (Horizontal Rule) element" slug: Web/HTML/Element/hr page-type: html-element browser-compat: html.elements.hr --- {{HTMLSidebar}} The **`<hr>`** [HTML](/en-US/docs/Web/HTML) element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section. {{EmbedInteractiveExample("pages/tabbed/hr.html", "tabbed-shorter")}} Historically, this has been presented as a horizontal rule or line. While it may still be displayed as a horizontal rule in visual browsers, this element is now defined in semantic terms, rather than presentational terms, so if you wish to draw a horizontal line, you should do so using appropriate CSS. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `align` {{deprecated_inline}} {{Non-standard_Inline}} - : Sets the alignment of the rule on the page. If no value is specified, the default value is `left`. - `color` {{deprecated_inline}} {{Non-standard_Inline}} - : Sets the color of the rule through color name or hexadecimal value. - `noshade` {{deprecated_inline}} {{Non-standard_Inline}} - : Sets the rule to have no shading. - `size` {{deprecated_inline}} {{Non-standard_Inline}} - : Sets the height, in pixels, of the rule. - `width` {{deprecated_inline}} {{Non-standard_Inline}} - : Sets the length of the rule on the page through a pixel or percentage value. ## Example ### HTML ```html <p> This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. This is the first paragraph of text. </p> <hr /> <p> This is the second paragraph of text. This is the second paragraph of text. This is the second paragraph of text. This is the second paragraph of text. </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 >. </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> <ul> <li>Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#flow_content">flow content</a></li> <li><a href="/en-US/docs/Web/HTML/Element/select"><code>&lt;select></code></a> element</li> </ul> </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role"><code>separator</code></a></td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLHRElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement('p')}} - [`<hr>` in `<select>`](/en-US/docs/Web/HTML/Element/select#hr_in_select)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/center/index.md
--- title: "<center>: The Centered Text element" slug: Web/HTML/Element/center page-type: html-element status: - deprecated browser-compat: html.elements.center --- {{HTMLSidebar}}{{deprecated_header}} The **`<center>`** [HTML](/en-US/docs/Web/HTML) element is a [block-level element](/en-US/docs/Glossary/Block-level_content) that displays its block-level or inline contents centered horizontally within its containing element. The container is usually, but isn't required to be, {{HTMLElement("body")}}. This tag has been deprecated in HTML 4 (and XHTML 1) in favor of the [CSS](/en-US/docs/Web/CSS) {{Cssxref("text-align")}} property, which can be applied to the {{HTMLElement("div")}} element or to an individual {{HTMLElement("p")}}. For centering blocks, use other CSS properties like {{Cssxref("margin-left")}} and {{Cssxref("margin-right")}} and set them to `auto` (or set {{Cssxref("margin")}} to `0 auto`). ## DOM interface This element implements the {{domxref("HTMLElement")}} interface. ## Example 1 ```html <center> This text will be centered. <p>So will this paragraph.</p> </center> ``` ### Result {{EmbedLiveSample("Example 1")}} ## Example 2 (CSS alternative) ```html <div style="text-align:center"> This text will be centered. <p>So will this paragraph.</p> </div> ``` ### Result {{EmbedLiveSample("Example 2 (CSS alternative)")}} ## Example 3 (CSS alternative) ```html <p style="text-align:center"> This line will be centered.<br /> And so will this line. </p> ``` ### Result {{EmbedLiveSample("Example 3 (CSS alternative)")}} > **Note:** Applying {{Cssxref("text-align")}}`:center` to a {{HTMLElement("div")}} or {{HTMLElement("p")}} element centers the _contents_ of those elements while leaving their overall dimensions unchanged. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{Cssxref("text-align")}} - {{Cssxref("display")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/track/index.md
--- title: "<track>: The Embed Text Track element" slug: Web/HTML/Element/track page-type: html-element browser-compat: html.elements.track --- {{HTMLSidebar}} The **`<track>`** [HTML](/en-US/docs/Web/HTML) element is used as a child of the media elements, {{HTMLElement("audio")}} and {{HTMLElement("video")}}. It lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles. The tracks are formatted in [WebVTT format](/en-US/docs/Web/API/WebVTT_API) (`.vtt` files) — Web Video Text Tracks. {{EmbedInteractiveExample("pages/tabbed/track.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `default` - : This attribute indicates that the track should be enabled unless the user's preferences indicate that another track is more appropriate. This may only be used on one `track` element per media element. - `kind` - : How the text track is meant to be used. If omitted the default kind is `subtitles`. If the attribute contains an invalid value, it will use `metadata` (Versions of Chrome earlier than 52 treated an invalid value as `subtitles`). The following keywords are allowed: - `subtitles` - Subtitles provide translation of content that cannot be understood by the viewer. For example speech or text that is not English in an English language film. - Subtitles may contain additional content, usually extra background information. For example the text at the beginning of the Star Wars films, or the date, time, and location of a scene. - `captions` - Closed captions provide a transcription and possibly a translation of audio. - It may include important non-verbal information such as music cues or sound effects. It may indicate the cue's source (e.g. music, text, character). - Suitable for users who are deaf or when the sound is muted. - `descriptions` - Textual description of the video content. - Suitable for users who are blind or where the video cannot be seen. - `chapters` - Chapter titles are intended to be used when the user is navigating the media resource. - `metadata` - Tracks used by scripts. Not visible to the user. - `label` - : A user-readable title of the text track which is used by the browser when listing available text tracks. - `src` - : Address of the track (`.vtt` file). Must be a valid URL. This attribute must be specified and its URL value must have the same origin as the document — unless the {{HTMLElement("audio")}} or {{HTMLElement("video")}} parent element of the `track` element has a [`crossorigin`](/en-US/docs/Web/HTML/Attributes/crossorigin) attribute. - `srclang` - : Language of the track text data. It must be a valid [BCP 47](https://r12a.github.io/app-subtags/) language tag. If the `kind` attribute is set to `subtitles`, then `srclang` must be defined. ## Usage notes ### Track data types The type of data that `track` adds to the media is set in the `kind` attribute, which can take values of `subtitles`, `captions`, `descriptions`, `chapters` or `metadata`. The element points to a source file containing timed text that the browser exposes when the user requests additional data. A media element cannot have more than one `track` with the same `kind`, `srclang`, and `label`. ### Detecting cue changes The underlying {{domxref("TextTrack")}}, indicated by the {{domxref("HTMLTrackElement.track", "track")}} property, receives a `cuechange` event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element. If the track _is_ associated with a media element, using the {{HTMLElement("track")}} element as a child of the {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, the `cuechange` event is also sent to the {{domxref("HTMLTrackElement")}}. ```js let textTrackElem = document.getElementById("texttrack"); textTrackElem.addEventListener("cuechange", (event) => { let cues = event.target.track.activeCues; }); ``` ## Examples ```html <video controls poster="/images/sample.gif"> <source src="sample.mp4" type="video/mp4" /> <source src="sample.ogv" type="video/ogv" /> <track kind="captions" src="sampleCaptions.vtt" srclang="en" /> <track kind="descriptions" src="sampleDescriptions.vtt" srclang="en" /> <track kind="chapters" src="sampleChapters.vtt" srclang="en" /> <track kind="subtitles" src="sampleSubtitles_de.vtt" srclang="de" /> <track kind="subtitles" src="sampleSubtitles_en.vtt" srclang="en" /> <track kind="subtitles" src="sampleSubtitles_ja.vtt" srclang="ja" /> <track kind="subtitles" src="sampleSubtitles_oz.vtt" srclang="oz" /> <track kind="metadata" src="keyStage1.vtt" srclang="en" label="Key Stage 1" /> <track kind="metadata" src="keyStage2.vtt" srclang="en" label="Key Stage 2" /> <track kind="metadata" src="keyStage3.vtt" srclang="en" label="Key Stage 3" /> <!-- Fallback --> … </video> ``` ## 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> <p> A media element, {{HTMLElement("audio")}} or {{HTMLElement("video")}}. </p> </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("HTMLTrackElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebVTT text track format](/en-US/docs/Web/API/WebVTT_API) - {{domxref("HTMLMediaElement.textTracks")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/thead/index.md
--- title: "<thead>: The Table Head element" slug: Web/HTML/Element/thead page-type: html-element browser-compat: html.elements.thead --- {{HTMLSidebar}} The **`<thead>`** [HTML](/en-US/docs/Web/HTML) element encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the head of a table with information about the table's columns. This is usually in the form of column headers ({{HTMLElement("th")}} elements). {{EmbedInteractiveExample("pages/tabbed/thead.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 head 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. - `bgcolor` {{deprecated_inline}} - : Defines the background color of each head 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 head cell. If [`align`](#align) is not set to `char`, this attribute is ignored. - `charoff` {{deprecated_inline}} - : Specifies the number of characters to offset the head cell content from the alignment character specified by the [`char`](#char) attribute. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of each head 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 `<thead>` is placed after any {{HTMLElement("caption")}} and {{HTMLElement("colgroup")}} elements, but before any {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, and {{HTMLElement("tr")}} elements. - Along with its related {{HTMLElement("tbody")}} and {{HTMLElement("tfoot")}} elements, the `<thead>` element provides useful {{Glossary("semantics", "semantic")}} information and can be used when rendering for either screen or print. Specifying such table content groups also provides valuable contextual information for assistive technologies, including screen readers and search engines. - When printing a document, in the case of a multipage table, the table head usually specifies information that remains the same on each page. ## Examples See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. ### Basic head structure This example demonstrates a table divided into a head section with column headers and a body section with the table's main data. #### HTML The `<thead>` and {{HTMLElement("tbody")}} elements are used to structure the table rows into {{Glossary("semantics", "semantic")}} sections. The `<thead>` element represents the head section of the table, which contains a row ({{HTMLElement("tr")}}) of column headers cells ({{HTMLElement("th")}}). ```html <table> <thead> <tr> <th>Student ID</th> <th>Name</th> <th>Major</th> <th>Credits</th> </tr> </thead> <tbody> <tr> <td>3741255</td> <td>Jones, Martha</td> <td>Computer Science</td> <td>240</td> </tr> <tr> <td>3971244</td> <td>Nim, Victor</td> <td>Russian Literature</td> <td>220</td> </tr> <tr> <td>4100332</td> <td>Petrov, Alexandra</td> <td>Astrophysics</td> <td>260</td> </tr> </tbody> </table> ``` #### CSS Some basic CSS is used to style and highlight the table head so that the headings of the columns stand out from the data in the table body. ```css thead { border-bottom: 2px solid rgb(160 160 160); text-align: center; background-color: #2c5e77; color: #fff; } tbody { background-color: #e4f0f5; } ``` ```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; } tbody > tr > td:last-of-type { text-align: center; } ``` #### Result {{EmbedLiveSample("Basic_head_structure", 650, 140)}} ### Multiple head rows This example demonstrates a table head section with two rows. #### HTML We extend the markup the table from the [basic example](#basic_head_structure) in this example by including two table rows ({{HTMLElement("tr")}}) within the `<thead>` element creating a multi-row table head. We included an additional column, splitting the student names into first and last names. ```html <table> <thead> <tr> <th rowspan="2">Student ID</th> <th colspan="2">Student</th> <th rowspan="2">Major</th> <th rowspan="2">Credits</th> </tr> <tr> <th>First name</th> <th>Last name</th> </tr> </thead> <tbody> <tr> <td>3741255</td> <td>Martha</td> <td>Jones</td> <td>Computer Science</td> <td>240</td> </tr> <tr> <td>3971244</td> <td>Victor</td> <td>Nim</td> <td>Russian Literature</td> <td>220</td> </tr> <tr> <td>4100332</td> <td>Alexandra</td> <td>Petrov</td> <td>Astrophysics</td> <td>260</td> </tr> </tbody> </table> ``` #### Cell spanning In order to associate and line up the header cells with the correct columns and rows, the [`colspan`](/en-US/docs/Web/HTML/Element/th#colspan) and [`rowspan`](/en-US/docs/Web/HTML/Element/th#rowspan) attributes are used on the {{HTMLElement("th")}} elements. The values set in these attributes specify how many cells each header cell ({{HTMLElement("th")}}) spans. Due to the way these attributes are set, the two second-row header cells are lined up with the columns they head. These each span one row and one column as the default values for the [`colspan`](/en-US/docs/Web/HTML/Element/th#colspan) and [`rowspan`](/en-US/docs/Web/HTML/Element/th#rowspan) attributes are both `1`. The column and row spanning demonstrated by this example are illustrated in the following figure: ![Illustration demonstrating column and row spanning of table cells: cells 1, 3, and 4 spanning one column and two rows each; cell 2 spanning two columns and one row; cells 5 and 6 span a single row and column each, fitting into the available cells that are the second and third columns in the second row](column-row-span.png) #### CSS The CSS is unchanged from the [previous example](#basic_head_structure). ```css hidden thead { border-bottom: 2px solid rgb(160 160 160); background-color: #2c5e77; color: #fff; } table { border-collapse: collapse; border: 2px solid rgb(140 140 140); font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } tbody { background-color: #e4f0f5; } th, td { border: 1px solid rgb(160 160 160); padding: 8px 10px; } tbody > tr > td:last-of-type { text-align: center; } ``` #### Result {{EmbedLiveSample("Multiple_head_rows", 650, 180)}} ## 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("tr")}} elements.</td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is mandatory. The end tag may be omitted if the {{HTMLElement("thead")}} element is immediately followed by a {{HTMLElement("tbody")}} or {{HTMLElement("tfoot")}} element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("table")}} element. The {{HTMLElement("thead")}} must appear after any {{HTMLElement("caption")}} and {{HTMLElement("colgroup")}} elements, even implicitly defined, but before any {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, and {{HTMLElement("tr")}} elements. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Rowgroup_Role" >rowgroup</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("HTMLTableSectionElement")}}</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("tr")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each head cell - {{cssxref("border")}}: CSS property to control borders of head cells - {{cssxref("text-align")}}: CSS property to horizontally align each head cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each head cell content
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/thead/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/address/index.md
--- title: "<address>: The Contact Address element" slug: Web/HTML/Element/address page-type: html-element browser-compat: html.elements.address --- {{HTMLSidebar}} The **`<address>`** [HTML](/en-US/docs/Web/HTML) element indicates that the enclosed HTML provides contact information for a person or people, or for an organization. {{EmbedInteractiveExample("pages/tabbed/address.html", "tabbed-standard")}} The contact information provided by an `<address>` element's contents can take whatever form is appropriate for the context, and may include any type of contact information that is needed, such as a physical address, URL, email address, phone number, social media handle, geographic coordinates, and so forth. The `<address>` element should include the name of the person, people, or organization to which the contact information refers. `<address>` can be used in a variety of contexts, such as providing a business's contact information in the page header, or indicating the author of an article by including an `<address>` element within the {{HTMLElement("article")}}. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - The `<address>` element can only be used to represent the contact information for its nearest {{HTMLElement("article")}} or {{HTMLElement("body")}} element ancestor. - This element should not contain more information than the contact information, like a publication date (which belongs in a {{HTMLElement("time")}} element). - Typically an `<address>` element can be placed inside the {{HTMLElement("footer")}} element of the current section, if any. ## Examples This example demonstrates the use of `<address>` to demarcate the contact information for an article's author. ```html <address> You can contact author at <a href="http://www.example.com/contact">www.example.com</a>.<br /> If you see any bugs, please <a href="mailto:[email protected]">contact webmaster</a>.<br /> You may also want to visit us:<br /> Mozilla Foundation<br /> 331 E Evelyn Ave<br /> Mountain View, CA 94041<br /> USA </address> ``` ### Result {{EmbedLiveSample("Examples", "300", "200")}} Although it renders text with the same default styling as the {{HTMLElement("i")}} or {{HTMLElement("em")}} elements, it is more appropriate to use `<address>` when dealing with contact information, as it conveys additional semantic 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> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, palpable content. </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 nested <code>&#x3C;address></code> element, no heading content ({{HTMLElement("hgroup")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}), no sectioning content ({{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}}), and no {{HTMLElement("header")}} or {{HTMLElement("footer")}} element. </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#flow_content" >flow content</a >, but always excluding <code>&#x3C;address></code> elements (according to the logical principle of symmetry, if <code>&#x3C;address></code> tag, as a parent, can not have nested <code>&#x3C;address></code> element, then the same <code>&#x3C;address></code> content can not have <code>&#x3C;address></code> tag as its parent). </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/group_role" >group</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")}} Prior to Gecko 2.0 (Firefox 4), Gecko implemented this element using the {{domxref("HTMLSpanElement")}} interface </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Others section-related elements: {{HTMLElement("body")}}, {{HTMLElement("nav")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("Heading_Elements", "h1")}}, {{HTMLElement("Heading_Elements", "h2")}}, {{HTMLElement("Heading_Elements", "h3")}}, {{HTMLElement("Heading_Elements", "h4")}}, {{HTMLElement("Heading_Elements", "h5")}}, {{HTMLElement("Heading_Elements", "h6")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("footer")}}, {{HTMLElement("section")}}, {{HTMLElement("header")}}; - [Sections and outlines of an HTML document](/en-US/docs/Web/HTML/Element/Heading_Elements).
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/wbr/index.md
--- title: "<wbr>: The Line Break Opportunity element" slug: Web/HTML/Element/wbr page-type: html-element browser-compat: html.elements.wbr --- {{HTMLSidebar}} The **`<wbr>`** [HTML](/en-US/docs/Web/HTML) element represents a word break opportunity—a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location. {{EmbedInteractiveExample("pages/tabbed/wbr.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Notes On UTF-8 encoded pages, `<wbr>` behaves like the `U+200B ZERO-WIDTH SPACE` code point. In particular, it behaves like a Unicode bidi BN code point, meaning it has no effect on {{Glossary("bidi")}}-ordering: `<div dir=rtl>123,<wbr>456</div>` displays, when not broken on two lines, `123,456` and not `456,123`. For the same reason, the `<wbr>` element does not introduce a hyphen at the line break point. To make a hyphen appear only at the end of a line, use the soft hyphen character entity (`&shy;`) instead. ## Examples _[The Yahoo Style Guide](https://web.archive.org/web/20121014054923/http://styleguide.yahoo.com/)_ recommends [breaking a URL _before_ punctuation](https://web.archive.org/web/20121105171040/http://styleguide.yahoo.com/editing/treat-abbreviations-capitalization-and-titles-consistently/website-names-and-addresses), to avoid leaving a punctuation mark at the end of the line, which the reader might mistake for the end of the URL. ```html <p> http://this<wbr />.is<wbr />.a<wbr />.really<wbr />.long<wbr />.example<wbr />.com/With<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages<wbr />/deeper<wbr />/level<wbr />/pages </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 >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td>Empty</td> </tr> <tr> <th scope="row">Tag omission</th> <td> It is a {{Glossary("void element")}}; it must have a start tag, but must not have 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 >. </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 - {{cssxref("overflow-wrap")}} - {{cssxref("word-break")}} - {{cssxref("hyphens")}} - The {{HTMLElement("br")}} element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/rp/index.md
--- title: "<rp>: The Ruby Fallback Parenthesis element" slug: Web/HTML/Element/rp page-type: html-element browser-compat: html.elements.rp --- {{HTMLSidebar}} The **`<rp>`** [HTML](/en-US/docs/Web/HTML) element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the {{HTMLElement("ruby") }} element. One `<rp>` element should enclose each of the opening and closing parentheses that wrap the {{HTMLElement("rt")}} element that contains the annotation's text. {{EmbedInteractiveExample("pages/tabbed/rp.html", "tabbed-shorter")}} ## 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 `<rp>` element is used in the case of lack of {{HTMLElement("ruby")}} element support; the `<rp>` content provides what should be displayed in order to indicate the presence of a ruby annotation, usually parentheses. ## Examples ### Using ruby annotations This example uses ruby annotations to display the [Romaji](https://en.wikipedia.org/wiki/Romaji) equivalents for each character. ```html <ruby> 漢 <rp>(</rp><rt>Kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> ``` ```css hidden body { font-size: 22px; } ``` #### Result {{EmbedLiveSample("Using_ruby_annotations", 600, 60)}} See the article about the {{HTMLElement("ruby")}} element for further examples. ### Without ruby support If your browser does not support ruby annotations, the result looks like this instead: ```html hidden 漢 (Kan) 字 (ji) ``` ```css hidden body { font-size: 22px; } ``` {{EmbedLiveSample("Without_ruby_support", 600, 60)}} ## 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>Text</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")}} or another <code>&#x3C;rp></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. <code>&#x3C;rp></code> must be positioned immediately before or after an {{HTMLElement("rt")}} 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>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("rb")}} - {{HTMLElement("rtc")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/marquee/index.md
--- title: "<marquee>: The Marquee element" slug: Web/HTML/Element/marquee page-type: html-element status: - deprecated browser-compat: html.elements.marquee --- {{HTMLSidebar}}{{Deprecated_Header}} The **`<marquee>`** [HTML](/en-US/docs/Web/HTML) element is used to insert a scrolling area of text. You can control what happens when the text reaches the edges of its content area using its attributes. ## Attributes - `behavior` {{Deprecated_Inline}} - : Sets how the text is scrolled within the marquee. Possible values are `scroll`, `slide` and `alternate`. If no value is specified, the default value is `scroll`. - `bgcolor` {{Deprecated_Inline}} - : Sets the background color through color name or hexadecimal value. - `direction` {{Deprecated_Inline}} - : Sets the direction of the scrolling within the marquee. Possible values are `left`, `right`, `up` and `down`. If no value is specified, the default value is `left`. - `height` {{Deprecated_Inline}} - : Sets the height in pixels or percentage value. - `hspace` {{Deprecated_Inline}} - : Sets the horizontal margin - `loop` {{Deprecated_Inline}} - : Sets the number of times the marquee will scroll. If no value is specified, the default value is −1, which means the marquee will scroll continuously. - `scrollamount` {{Deprecated_Inline}} - : Sets the amount of scrolling at each interval in pixels. The default value is 6. - `scrolldelay` {{Deprecated_Inline}} - : Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead unless `truespeed` is specified. - `truespeed` {{Deprecated_Inline}} - : By default, `scrolldelay` values lower than 60 are ignored. If `truespeed` is present, those values are not ignored. - `vspace` {{Deprecated_Inline}} - : Sets the vertical margin in pixels or percentage value. - `width` {{Deprecated_Inline}} - : Sets the width in pixels or percentage value. ## Event handlers - `onbounce` - : Fires when the marquee has reached the end of its scroll position. It can only fire when the behavior attribute is set to `alternate`. - `onfinish` - : Fires when the marquee has finished the amount of scrolling that is set by the loop attribute. It can only fire when the loop attribute is set to some number that is greater than 0. - `onstart` - : Fires when the marquee starts scrolling. ## Methods - `start()` - : Starts scrolling of the marquee. - `stop()` - : Stops scrolling of the marquee. ## Examples ```html <marquee>This text will scroll from right to left</marquee> <marquee direction="up">This text will scroll from bottom to top</marquee> <marquee direction="down" width="250" height="200" behavior="alternate" style="border:solid"> <marquee behavior="alternate">This text will bounce</marquee> </marquee> ``` ### Result {{EmbedLiveSample("Examples", 600, 450)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLMarqueeElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("HTMLMarqueeElement")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/option/index.md
--- title: "<option>: The HTML Option element" slug: Web/HTML/Element/option page-type: html-element browser-compat: html.elements.option --- {{HTMLSidebar}} The **`<option>`** [HTML](/en-US/docs/Web/HTML) element is used to define an item contained in a {{HTMLElement("select")}}, an {{HTMLElement("optgroup")}}, or a {{HTMLElement("datalist")}} element. As such, `<option>` can represent menu items in popups and other lists of items in an HTML document. {{EmbedInteractiveExample("pages/tabbed/option.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `disabled` - : If this Boolean attribute is set, this option is not checkable. Often browsers grey out such control and it won't receive any browsing event, like mouse clicks or focus-related ones. If this attribute is not set, the element can still be disabled if one of its ancestors is a disabled {{HTMLElement("optgroup")}} element. - `label` - : This attribute is text for the label indicating the meaning of the option. If the `label` attribute isn't defined, its value is that of the element text content. - `selected` - : If present, this Boolean attribute indicates that the option is initially selected. If the `<option>` element is the descendant of a {{HTMLElement("select")}} element whose [`multiple`](/en-US/docs/Web/HTML/Element/select#multiple) attribute is not set, only one single `<option>` of this {{HTMLElement("select")}} element may have the `selected` attribute. - `value` - : The content of this attribute represents the value to be submitted with the form, should this option be selected. If this attribute is omitted, the value is taken from the text content of the option element. ## Styling with CSS Styling the **`<option>`** element is highly limited. Options don't inherit the font set on the parent. In Firefox, only [`color`](/en-US/docs/Web/CSS/color) and [`background-color`](/en-US/docs/Web/CSS/background-color) can be set, however in Chrome and Safari it's not possible to set any properties. You can find more details about styling in [our guide to advanced form styling](/en-US/docs/Learn/Forms/Advanced_form_styling). ## Examples See {{HTMLElement("select")}} for 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> Text, possibly with escaped characters (like <code>&#x26;eacute;</code>). </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag is mandatory. The end tag is optional if this element is immediately followed by another <code>&#x3C;option></code> element or an {{HTMLElement("optgroup")}}, or if the parent element has no more content. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("select")}}, an {{HTMLElement("optgroup")}} or a {{HTMLElement("datalist")}} element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/option_role"><code>option</code></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("HTMLOptionElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other form-related elements: {{HTMLElement("form")}}, {{HTMLElement("legend")}}, {{HTMLElement("label")}}, {{HTMLElement("button")}}, {{HTMLElement("select")}}, {{HTMLElement("datalist")}}, {{HTMLElement("optgroup")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("textarea")}}, {{HTMLElement("input")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}} and {{HTMLElement("meter")}}.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/xmp/index.md
--- title: <xmp> slug: Web/HTML/Element/xmp page-type: html-element status: - deprecated browser-compat: html.elements.xmp --- {{HTMLSidebar}}{{deprecated_header}} ## Summary The **`<xmp>`** [HTML](/en-US/docs/Web/HTML) element renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML2 specification recommended that it should be rendered wide enough to allow 80 characters per line. > **Note:** Do not use this element. > > - It has been deprecated since HTML3.2 and was not implemented in a consistent way. It was completely removed from current HTML. > - Use the {{HTMLElement("pre")}} element or, if semantically adequate, the {{HTMLElement("code")}} element instead. Note that you will need to escape the '`<`' character as '`&lt;`' and the '`&`' character as '`&amp;`' to make sure they are not interpreted as markup. > - A monospaced font can also be obtained on any element, by applying an adequate [CSS](/en-US/docs/Web/CSS) style using `monospace` as the generic-font value for the {{cssxref("font-family")}} property. ## Attributes This element has no other attributes than the [global attributes](/en-US/docs/Web/HTML/Global_attributes), common to all elements. ## DOM interface This element implements the {{domxref('HTMLElement')}} interface. <!-- ## Technical summary --> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("pre")}} and {{HTMLElement("code")}} elements to be used instead. - The {{HTMLElement("plaintext")}} element, similar to {{HTMLElement("xmp")}} but also obsolete.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/label/index.md
--- title: "<label>: The Label element" slug: Web/HTML/Element/label page-type: html-element browser-compat: html.elements.label --- {{HTMLSidebar}} The **`<label>`** [HTML](/en-US/docs/Web/HTML) element represents a caption for an item in a user interface. {{EmbedInteractiveExample("pages/tabbed/label.html", "tabbed-shorter")}} Associating a `<label>` with a form control, such as {{htmlelement("input")}} or {{htmlelement("textarea")}} offers some major advantages: - The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered. - When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device. To explicitly associate a `<label>` element with an `<input>` element, you first need to add the `id` attribute to the `<input>` element. Next, you add the `for` attribute to the `<label>` element, where the value of `for` is the same as the `id` in the `<input>` element. Alternatively, you can nest the `<input>` directly inside the `<label>`, in which case the `for` and `id` attributes are not needed because the association is implicit: ```html <label> Do you like peas? <input type="checkbox" name="peas" /> </label> ``` The form control that a label is labeling is called the _labeled control_ of the label element. Multiple labels can be associated with the same form control: ```html <label for="username">Enter your username:</label> <input id="username" name="username" type="text" /> <label for="username">Forgot your username?</label> ``` Elements that can be associated with a `<label>` element include {{HTMLElement('button')}}, {{HTMLElement('input')}} (except for `type="hidden"`), {{HTMLElement('meter')}}, {{HTMLElement('output')}}, {{HTMLElement('progress')}}, {{HTMLElement('select')}} and {{HTMLElement('textarea')}}. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `for` - : The value of the `for` attribute must be a single [`id`](/en-US/docs/Web/HTML/Global_attributes#id) for a [labelable](/en-US/docs/Web/HTML/Content_categories#labelable) form-related element in the same document as the `<label>` element. So, any given `label` element can be associated with only one form control. > **Note:** To programmatically set the `for` attribute, use [`htmlFor`](/en-US/docs/Web/API/HTMLLabelElement/htmlFor). The first element in the document with an `id` attribute matching the value of the `for` attribute is the _labeled control_ for this `label` element — if the element with that `id` is actually a [labelable element](https://html.spec.whatwg.org/multipage/forms.html#category-label). If it is _not_ a labelable element, then the `for` attribute has no effect. If there are other elements that also match the `id` value, later in the document, they are not considered. Multiple `label` elements can be given the same value for their `for` attribute; doing so causes the associated form control (the form control that `for` value references) to have multiple labels. > **Note:** A `<label>` element can have both a `for` attribute and a contained control element, as long as the `for` attribute points to the contained control element. ## Styling with CSS There are no special styling considerations for `<label>` elements — structurally they are simple inline elements, and so can be styled in much the same way as a {{htmlelement("span")}} or {{htmlelement("a")}} element. You can apply styling to them in any way you want, as long as you don't cause the text to become difficult to read. ## Examples ### Defining an implicit label ```html <label>Click me <input type="text" /></label> ``` {{EmbedLiveSample('Simple_label_example', '200', '50')}} ### Defining an explicit label with the "for" attribute ```html <label for="username">Click me to focus on the input field</label> <input type="text" id="username" /> ``` {{EmbedLiveSample('Using_the_for_attribute', '200', '50')}} ## Accessibility concerns ### Interactive content Don't place interactive elements such as {{HTMLElement("a", "anchors")}} or {{HTMLElement("button", "buttons")}} inside a `label`. Doing so makes it difficult for people to activate the form input associated with the `label`. **Don't do this:** ```html example-bad <label for="tac"> <input id="tac" type="checkbox" name="terms-and-conditions" /> I agree to the <a href="terms-and-conditions.html">Terms and Conditions</a> </label> ``` **Prefer this:** ```html example-good <label for="tac"> <input id="tac" type="checkbox" name="terms-and-conditions" /> I agree to the Terms and Conditions </label> <p> <a href="terms-and-conditions.html">Read our Terms and Conditions</a> </p> ``` ### Headings Placing [heading elements](/en-US/docs/Web/HTML/Element/Heading_Elements) within a `<label>` interferes with many kinds of assistive technology, because headings are commonly used as [a navigation aid](/en-US/docs/Web/HTML/Element/Heading_Elements#navigation). If the label's text needs to be adjusted visually, use CSS classes applied to the `<label>` element instead. If a [form](/en-US/docs/Web/HTML/Element/form), or a section of a form needs a title, use the {{HTMLElement("legend")}} element placed within a {{HTMLElement("fieldset")}}. **Don't do this:** ```html example-bad <label for="your-name"> <h3>Your name</h3> <input id="your-name" name="your-name" type="text" /> </label> ``` **Prefer this:** ```html example-good <label class="large-label" for="your-name"> Your name <input id="your-name" name="your-name" type="text" /> </label> ``` ### Buttons An {{HTMLElement("input")}} element with a `type="button"` declaration and a valid `value` attribute does not need a label associated with it. Doing so may actually interfere with how assistive technology parses the button input. The same applies for the {{HTMLElement("button")}} element. ## 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#interactive_content" >interactive content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#form-associated_content" >form-associated element</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 >, but no descendant <code>label</code> elements. No <a href="/en-US/docs/Web/HTML/Content_categories#labelable" >labelable</a > elements other than the labeled control are allowed. </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("HTMLLabelElement")}}</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/u/index.md
--- title: "<u>: The Unarticulated Annotation (Underline) element" slug: Web/HTML/Element/u page-type: html-element browser-compat: html.elements.u --- {{HTMLSidebar}} The **`<u>`** [HTML](/en-US/docs/Web/HTML) element represents a span of inline text which should be rendered in a way that indicates that it has a non-textual annotation. This is rendered by default as a simple solid underline, but may be altered using CSS. > **Warning:** This element used to be called the "Underline" element in older versions of HTML, and is still sometimes misused in this way. To underline text, you should instead apply a style that includes the CSS {{cssxref("text-decoration")}} property set to `underline`. {{EmbedInteractiveExample("pages/tabbed/u.html", "tabbed-shorter")}} See the [Usage notes](#usage_notes) section for further details on when it's appropriate to use `<u>` and when it isn't. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes Along with other pure styling elements, the original HTML Underline (`<u>`) element was deprecated in HTML 4; however, `<u>` was restored in HTML 5 with a new, semantic, meaning: to mark text as having some form of non-textual annotation applied. > **Note:** Avoid using the `<u>` element with its default styling (of underlined text) in such a way as to be confused with a hyperlink, which is also underlined by default. ### Use cases Valid use cases for the `<u>` element include annotating spelling errors, applying a [proper name mark](https://en.wikipedia.org/wiki/Proper_name_mark) to denote proper names in Chinese text, and other forms of annotation. You should _not_ use `<u>` to underline text for presentation purposes, or to denote titles of books. ### Other elements to consider using In most cases, you should use an element other than `<u>`, such as: - {{HTMLElement("em")}} to denote stress emphasis - {{HTMLElement("b")}} to draw attention to text - {{HTMLElement("mark")}} to mark key words or phrases - {{HTMLElement("strong")}} to indicate that text has strong importance - {{HTMLElement("cite")}} to mark the titles of books or other publications - {{HTMLElement("i")}} to denote technical terms, transliterations, thoughts, or names of vessels in Western texts To provide textual annotations (as opposed to the non-textual annotations created with `<u>`), use the {{HTMLElement("ruby")}} element. To apply an underlined appearance without any semantic meaning, use the {{cssxref("text-decoration")}} property's value `underline`. ## Examples ### Indicating a spelling error This example uses the `<u>` element and some CSS to display a paragraph which includes a misspelled error, with the error indicated in the red wavy underline style which is fairly commonly used for this purpose. #### HTML ```html <p>This paragraph includes a <u class="spelling">wrnogly</u> spelled word.</p> ``` In the HTML, we see the use of `<u>` with a class, `spelling`, which is used to indicate the misspelling of the word "wrongly". #### CSS ```css u.spelling { text-decoration: red wavy underline; } ``` This CSS indicates that when the `<u>` element is styled with the class `spelling`, it should have a red wavy underline underneath its text. This is a common styling for spelling errors. Another common style can be presented using `red dashed underline`. #### Result The result should be familiar to anyone who has used any of the more popular word processors available today. {{EmbedLiveSample("Indicating_a_spelling_error", 650, 80)}} ### Avoiding \<u> Most of the time, you actually don't want to use `<u>`. Here are some examples that show what you should do instead in several cases. #### Non-semantic underlines To underline text without implying any semantic meaning, use a {{HTMLElement("span")}} element with the {{cssxref("text-decoration")}} property set to `"underline"`, as shown below. ##### HTML ```html <span class="underline">Today's Special</span> <br /> Chicken Noodle Soup With Carrots ``` ##### CSS ```css .underline { text-decoration: underline; } ``` ##### Result {{EmbedLiveSample("Non-semantic_underlines", 650, 80)}} #### Presenting a book title Book titles should be presented using the {{HTMLElement("cite")}} element instead of `<u>` or even `<i>`. ##### Using the cite element ```html <p>The class read <cite>Moby Dick</cite> in the first term.</p> ``` {{EmbedLiveSample("Using_the_cite_element", 650, 80)}} ##### Styling the cite element The default styling for the `<cite>` element renders the text in italics. You can override that using CSS: ```html <p>The class read <cite>Moby Dick</cite> in the first term.</p> ``` ```css cite { font-style: normal; text-decoration: underline; } ``` {{EmbedLiveSample("Styling_the_cite_element", 650, 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/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 - The {{HTMLElement("span")}}, {{HTMLElement("i")}}, {{HTMLElement("em")}}, {{HTMLElement("b")}}, and {{HTMLElement("cite")}} elements should usually be used instead. - The CSS {{cssxref("text-decoration")}} property should be used for non-semantic underlining.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/code/index.md
--- title: "<code>: The Inline Code element" slug: Web/HTML/Element/code page-type: html-element browser-compat: html.elements.code --- {{HTMLSidebar}} The **`<code>`** [HTML](/en-US/docs/Web/HTML) element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the {{Glossary("user agent", "user agent's")}} default monospace font. {{EmbedInteractiveExample("pages/tabbed/code.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples A paragraph of text that includes `<code>`: ```html <p> The function <code>selectAll()</code> highlights all the text in the input field so the user can, for example, copy or delete the text. </p> ``` ### Result {{EmbedLiveSample("Example", 640, 70)}} ## Notes To represent multiple lines of code, wrap the `<code>` element within a {{HTMLElement("pre")}} element. The `<code>` element by itself only represents a single phrase of code or line of code. A CSS rule can be defined for the `code` selector to override the browser's default font face. Preferences set by the user might take precedence over the specified CSS. ## 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">code</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")}} 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("samp")}} - {{HTMLElement("kbd")}} - {{HTMLElement("var")}} - {{HTMLElement("pre")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/sub/index.md
--- title: "<sub>: The Subscript element" slug: Web/HTML/Element/sub page-type: html-element browser-compat: html.elements.sub --- {{HTMLSidebar}} The **`<sub>`** [HTML](/en-US/docs/Web/HTML) element specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text. {{EmbedInteractiveExample("pages/tabbed/sub.html", "tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<sub>` element should be used only 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, using `<sub>` to style the name of a company which uses altered baselines in their [wordmark](https://en.wikipedia.org/wiki/Wordmark) would not be appropriate; instead, CSS should be used. For example, you could use the {{cssxref("vertical-align")}} property with a declaration like `vertical-align: sub` or, to more precisely control the baseline shift, `vertical-align: -25%`. Appropriate use cases for `<sub>` include (but aren't necessarily limited to): - Marking up footnote numbers. See [Footnote numbers](#footnote_numbers) for an example. - Marking up the subscript in mathematical variable numbers (although you may also consider using a [MathML](/en-US/docs/Web/MathML) formula for this). See [Variable subscripts](#variable_subscripts). - Denoting the number of atoms of a given element within a chemical formula (such as every developer's best friend, C <sub>8</sub> H <sub>10</sub> N <sub>4</sub> O <sub>2</sub> , otherwise known as "caffeine"). See [Chemical formulas](#chemical_formulas). ## Examples ### Footnote numbers Traditional footnotes are denoted using numbers which are rendered in subscript. This is a common use case for `<sub>`: ```html <p> According to the computations by Nakamura, Johnson, and Mason<sub>1</sub> this will result in the complete annihilation of both particles. </p> ``` #### Result {{EmbedLiveSample("Footnote_numbers", 650, 80)}} ### Variable subscripts In mathematics, families of variables related to the same concept (such as distances along the same axis) are represented using the same variable name with a subscript following. For example: ```html-nolint <p> The horizontal coordinates' positions along the X-axis are represented as <var>x<sub>1</sub></var> … <var>x<sub>n</sub></var>. </p> ``` #### Result {{EmbedLiveSample("Variable_subscripts", 650, 80)}} ### Chemical formulas When writing a chemical formula, such as H<sub>2</sub>0, the number of atoms of a given element within the described molecule is represented using a subscripted number; in the case of water, the subscripted "2" indicates that there are two atoms of hydrogen in the molecule. Another example: ```html <p> Almost every developer's favorite molecule is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>, which is commonly known as "caffeine." </p> ``` #### Result {{EmbedLiveSample("Chemical_formulas", 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> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/structural_roles#structural_roles_with_html_equivalents">subscript</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("sup")}} HTML element that produces superscript. Note that you cannot use `sup` and `sub` both at the same time: you need to use [MathML](/en-US/docs/Web/MathML) to produce both a superscript directly above 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/rtc/index.md
--- title: "<rtc>: The Ruby Text Container element" slug: Web/HTML/Element/rtc page-type: html-element status: - deprecated browser-compat: html.elements.rtc --- {{HTMLSidebar}}{{deprecated_header}} The **`<rtc>`** [HTML](/en-US/docs/Web/HTML) element embraces semantic annotations of characters presented in a ruby of {{HTMLElement("rb")}} elements used inside of {{ HTMLElement("ruby") }} element. {{HTMLElement("rb")}} elements can have both pronunciation ({{HTMLElement("rt")}}) and semantic ({{HTMLElement("rtc")}}) annotations. {{EmbedInteractiveExample("pages/tabbed/rtc.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ```html <div class="info"> <ruby> <rtc> <rb>旧</rb><rt>jiù</rt> <rb>金</rb><rt>jīn</rt> <rb>山</rb><rt>shān</rt> </rtc> <rtc>San Francisco</rtc> </ruby> </div> ``` ```css hidden .info { padding-top: 10px; font-size: 36px; } ``` ### Result {{EmbedLiveSample("Examples", 600, 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>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a > or {{HTMLElement("rt")}} elements. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The closing tag can be omitted if it is immediately followed by a {{HTMLElement("rb")}}, {{HTMLElement("rtc")}} or {{HTMLElement("rt")}} element opening tag or by its parent closing tag. </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("rp")}} - {{HTMLElement("rb")}} - {{HTMLElement("rt")}}
0