<bdi>: The Bidirectional Isolate element - HTML: HyperText Markup Language

<bdi>: The Bidirectional Isolate element
========================================

The **`<bdi>`** 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.

Try it
------

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 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:
```

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:
```

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 `<span>` with the `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 `unicode-bidi``: isolate` on a `<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, except that the `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 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 `<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>
```

```
body {
  border: 1px solid #3f87a6;
  max-width: calc(100% - 40px - 6px);
  padding: 20px;
  width: calc(100% - 40px - 6px);
  border-width: 1px 1px 1px 5px;
}
```

### No bdi with RTL text

This example lists the winners of a competition using `<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>
```

```
body {
  border: 1px solid #3f87a6;
  max-width: calc(100% - 40px - 6px);
  padding: 20px;
  width: calc(100% - 40px - 6px);
  border-width: 1px 1px 1px 5px;
}
```

### 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>
```

```
body {
  border: 1px solid #3f87a6;
  max-width: calc(100% - 40px - 6px);
  padding: 20px;
  width: calc(100% - 40px - 6px);
  border-width: 1px 1px 1px 5px;
}
```

Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Flow content,
 phrasing content, palpable content.
  |
| Permitted content | Phrasing content. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 Any element that accepts
 phrasing content.
  |
| Implicit ARIA role | `generic` |
| Permitted ARIA roles | Any |
| DOM interface | `HTMLElement` |

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

| Specification |
| --- |
| HTML Standard # the-bdi-element |

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

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

See also
--------

* Inline markup and bidirectional text in HTML
* Unicode Bidirectional Algorithm basics
* Localization
* Related HTML element: `<bdo>`
* Related CSS properties: `direction`, `unicode-bidi`


<dt>: The Description Term element - HTML: HyperText Markup Language

<dt>: The Description Term element
==================================

The **`<dt>`** HTML element specifies a term in a description or definition list, and as such must be used inside a `<dl>` element. It is usually followed by a `<dd>` element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next `<dd>` element.

The subsequent `<dd>` (**Description Details**) element provides the definition or other related text associated with the term specified using `<dt>`.

Try it
------

Attributes
----------

This element only includes the global attributes.

Examples
--------

For examples, see the examples provided for the `<dl>` element.

Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | None. |
| Permitted content | Flow content, but with no `<header>`,
 `<footer>`, sectioning content or heading content
 descendants.
  |
| Tag omission |
 The start tag is required. The end tag may be omitted if this element is
 immediately followed by another `<dt>` element or a
 `<dd>` element, or if there is no more content in
 the parent element.
  |
| Permitted parents |
 A `<dl>` or (in WHATWG HTML,
 W3C HTML 5.2 and later) a
 `<div>` that is a child of a
 `<dl>`.This element can be used before a
 `<dd>` or another `<dt>`
 element.
  |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | `listitem` |
| DOM interface | `HTMLElement` Up to Gecko 1.9.2 (Firefox 4)
 inclusive, Firefox implements the
 `HTMLSpanElement` interface for this element.
  |

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

| Specification |
| --- |
| HTML Standard # the-dt-element |

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

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

See also
--------

* `<dl>`
* `<dd>`


<audio>: The Embed Audio element - HTML: HyperText Markup Language

<audio>: The Embed Audio element
================================

The **`<audio>`** 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 `<source>` element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a `MediaStream`.

Try it
------

The above example shows simple usage of the `<audio>` element. In a similar manner to the `<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.

`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 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`
Experimental

Non-standard

The `controlslist` 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 attribute indicates whether to use CORS to fetch the related audio file. CORS-enabled resources can be reused in the `<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 `<canvas>` elements. If invalid, it is handled as if the enumerated keyword **anonymous** was used. See CORS settings attributes 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 for more information.

In Safari, you can use `x-webkit-airplay="deny"` 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 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. This is optional; you may instead use the `<source>` element within the audio block to specify the audio to embed.

Events
------

| Event name | Fired when |
| --- | --- |
| `audioprocess` |
 The input buffer of a `ScriptProcessorNode` is
 ready to be processed.
  |
| `canplay` |
 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.
  |
| `canplaythrough` |
 The browser estimates it can play the media up to its end without
 stopping for content buffering.
  |
| `complete` |
 The rendering of an `OfflineAudioContext` is
 terminated.
  |
| `durationchange` | The `duration` attribute has been updated. |
| `emptied` |
 The media has become empty; for example, this event is sent if the media
 has already been loaded (or partially loaded), and the
 `HTMLMediaElement.load` method is called to
 reload it.
  |
| `ended` | Playback has stopped because the end of the media was reached. |
| `loadeddata` | The first frame of the media has finished loading. |
| `loadedmetadata` | The metadata has been loaded. |
| `loadstart` | Fired when the browser has started to load the resource. |
| `pause` | Playback has been paused. |
| `play` | Playback has begun. |
| `playing` |
 Playback is ready to start after having been paused or delayed due to
 lack of data.
  |
| `ratechange` | The playback rate has changed. |
| `seeked` | A *seek* operation completed. |
| `seeking` | A *seek* operation began. |
| `stalled` |
 The user agent is trying to fetch media data, but data is unexpectedly
 not forthcoming.
  |
| `suspend` | Media data loading has been suspended. |
| `timeupdate` |
 The time indicated by the `currentTime` attribute has been
 updated.
  |
| `volumechange` | The volume has changed. |
| `waiting` | Playback has stopped because of a temporary lack of data |

Usage notes
-----------

Browsers don't all support the same file types and audio codecs; you can provide multiple sources inside nested `<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">MP3</a> or
    <a href="myAudio.ogg">OGG</a> audio.
  </p>
</audio>
```

We offer a substantive and thorough guide to media file types and the audio codecs that can be used within them. Also available is a guide to the codecs supported for video.

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 `HTMLMediaElement` API.
* To allow precise control over your audio content, `HTMLMediaElement`s fire many different 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 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 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 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 `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 `border` and `border-radius`, `padding`, `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 `HTMLMediaElement` API to wire up their functionality.

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 `addtrack` and `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 `HTMLMediaElement` that corresponds to the type of track that was added to the element:

`HTMLMediaElement.audioTracks`

An `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.

`HTMLMediaElement.videoTracks`

Add an `addtrack` listener to this `VideoTrackList` object to be informed when video tracks are added to the element.

`HTMLMediaElement.textTracks`

Add an `addtrack` event listener to this `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 `addEventListener()` to listen for the `addtrack` and `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 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.

### <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 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, 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 `<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.
```

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">OGG</a> audio.
  </p>
</audio>
```

* Web Video Text Tracks Format (WebVTT)
* WebAIM: Captions, Transcripts, and Audio Descriptions
* MDN Understanding WCAG, Guideline 1.2 explanations
* Understanding Success Criterion 1.2.1 | W3C Understanding WCAG 2.0
* Understanding Success Criterion 1.2.2 | W3C Understanding WCAG 2.0
Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Flow content, phrasing content, embedded content. If it has a
 `controls` attribute: interactive
 content and palpable content.
  |
| Permitted content |
 If the element has a `src`
 attribute: zero or more `<track>` elements
 followed by transparent content that contains no
 `<audio>` or `<video>`
 media elements.Else: zero or more `<source>`
 elements followed by zero or more `<track>`
 elements followed by transparent content that contains no
 `<audio>` or `<video>`
 media elements.
  |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | `application` |
| DOM interface | `HTMLAudioElement` |

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

| Specification |
| --- |
| HTML Standard # the-audio-element |

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

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

See also
--------

* Web media technologies
    + Media container formats (file types)
    + Guide to audio codecs used on the web
* Web Audio API
* `HTMLAudioElement`
* `<source>`
* `<video>`
* Learning area: Video and audio content
* Cross-browser audio basics


<video>: The Video Embed element - HTML: HyperText Markup Language

<video>: The Video Embed element
================================

The **`<video>`** HTML element embeds a media player which supports video playback into the document. You can use `<video>` for audio content as well, but the `<audio>` element may provide a more appropriate user experience.

Try it
------

The above example shows simple usage of the `<video>` element. In a similar manner to the `<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.

`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 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`
Experimental

Non-standard

The `controlslist` 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` attribute if you want to disable the Picture-In-Picture mode (and the control).

`crossorigin`

This enumerated attribute indicates whether to use CORS to fetch the related video. CORS-enabled resources can be reused in the `<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 `<canvas>` elements. If invalid, it is handled as if the enumerated keyword `anonymous` was used. See CORS settings attributes for additional information.

`disablepictureinpicture`
Experimental

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"` as a fallback.

`height`

The height of the video's display area, in CSS pixels (absolute values only; no percentages).

`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 `<source>` element within the video block to specify the video to embed.

`width`

The width of the video's display area, in CSS pixels (absolute values only; no percentages).

Events
------

| Event Name | Fired When |
| --- | --- |
| `audioprocess`
Deprecated
 |
 The input buffer of a `ScriptProcessorNode` is
 ready to be processed.
  |
| `canplay` |
 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.
  |
| `canplaythrough` |
 The browser estimates it can play the media up to its end without
 stopping for content buffering.
  |
| `complete` |
 The rendering of an `OfflineAudioContext` is
 terminated.
  |
| `durationchange` | The `duration` attribute has been updated. |
| `emptied` |
 The media has become empty; for example, this event is sent if the media
 has already been loaded (or partially loaded), and the
 `load()`
 method is called to reload it.
  |
| `ended` | Playback has stopped because the end of the media was reached. |
| `error` |
 An error occurred while fetching the media data, or the type of the
 resource is not a supported media format.
  |
| `loadeddata` | The first frame of the media has finished loading. |
| `loadedmetadata` | The metadata has been loaded. |
| `loadstart` | Fired when the browser has started to load the resource. |
| `pause` | Playback has been paused. |
| `play` | Playback has begun. |
| `playing`  |
 Playback is ready to start after having been paused or delayed due to
 lack of data.
  |
| `progress` | Fired periodically as the browser loads a resource. |
| `ratechange` | The playback rate has changed. |
| `seeked` | A *seek* operation completed. |
| `seeking` | A *seek* operation began. |
| `stalled` |
 The user agent is trying to fetch media data, but data is unexpectedly
 not forthcoming.
  |
| `suspend` | Media data loading has been suspended. |
| `timeupdate` |
 The time indicated by the `currentTime` attribute has been
 updated.
  |
| `volumechange` | The volume has changed. |
| `waiting` | Playback has stopped because of a temporary lack of data. |

Usage notes
-----------

Browsers don't all support the same video formats; you can provide multiple sources inside nested `<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">link to the video</a> instead.
  </p>
</video>
```

We offer a substantive and thorough guide to media file types and the guide to the codecs supported for video. Also available is a guide to audio codecs that can be used with them.

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 `HTMLMediaElement` API. See Creating a cross-browser video player for more details.
* To allow precise control over your video (and audio) content, `HTMLMediaElement`s fire many different 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 `object-position` property to adjust the positioning of the video within the element's frame, and the `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 `<track>` element and the WebVTT format. See Adding captions and subtitles to HTML 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 transcript, since the `<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 beginner's tutorial.

### Styling with CSS

The `<video>` element is a replaced element — its `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 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 `addtrack` and `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 `HTMLMediaElement` that corresponds to the type of track that was added to the element:

`HTMLMediaElement.audioTracks`

An `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.

`HTMLMediaElement.videoTracks`

Add an `addtrack` listener to this `VideoTrackList` object to be informed when video tracks are added to the element.

`HTMLMediaElement.textTracks`

Add an `addtrack` event listener to this `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 `addEventListener()` to listen for the `addtrack` and `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`.
```

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`.
```

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

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 the MP4
  </a>
  and watch it with your favorite video player!
</video>
```

#### Result

First Ogg is tried. If that can't be played, then AVI is tried. Finally, 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` 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 video using VP8 for its video and 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 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 `<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:
```

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.

* Web Video Text Tracks Format (WebVTT)
* WebAIM: Captions, Transcripts, and Audio Descriptions
* MDN Understanding WCAG, Guideline 1.2 explanations
* Understanding Success Criterion 1.2.1 | W3C Understanding WCAG 2.0
* Understanding Success Criterion 1.2.2 | W3C Understanding WCAG 2.0
Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Flow content, phrasing content, embedded content. If it has a
 `controls` attribute: interactive
 content and palpable content.
  |
| Permitted content |
 If the element has a `src`
 attribute: zero or more `<track>` elements,
 followed by transparent content that contains no media elements–that
 is no `<audio>` or
 `<video>`.

 Else: zero or more `<source>` elements, followed
 by zero or more `<track>` elements, followed by
 transparent content that contains no media elements–that is no
 `<audio>` or `<video>`.
  |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents | Any element that accepts embedded content. |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | `application` |
| DOM interface | `HTMLVideoElement` |

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

| Specification |
| --- |
| HTML Standard # the-video-element |

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

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

See also
--------

* Guide to media types and formats on the web
    + Media container formats (file types)
    + Web video codec guide
    + Web audio codec guide
* Positioning and sizing the picture within its frame: `object-position` and `object-fit`
* `<audio>`
* Using HTML audio and video
* Manipulating video using canvas
* Configuring servers for Ogg media


<fieldset>: The Field Set element - HTML: HyperText Markup Language

<fieldset>: The Field Set element
=================================

The **`<fieldset>`** HTML element is used to group several controls as well as labels (`<label>`) within a web form.

Try it
------

As the example above shows, the `<fieldset>` element provides a grouping for a part of an HTML form, with a nested `<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 `<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.

`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 `<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 `<legend>` element won't be disabled.

`form`

This attribute takes the value of the `id` attribute of a `<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 `<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 `HTMLFormElement.elements`.

`name`

The name associated with the group.

**Note:** The caption for the fieldset is given by the first `<legend>` element nested inside it.

Styling with CSS
----------------

There are several special styling considerations for `<fieldset>`.

Its `display` value is `block` by default, and it establishes a 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 `min-inline-size: min-content` by default.

If a `<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

### 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

Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Flow content,
 sectioning root,
 listed,
 form-associated
 element, palpable content.
  |
| Permitted content |
 An optional `<legend>` element, followed by flow
 content.
  |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 Any element that accepts
 flow content.
  |
| Implicit ARIA role | `group` |
| Permitted ARIA roles | `radiogroup`,
 `presentation`, `none` |
| DOM interface | `HTMLFieldSetElement` |

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

| Specification |
| --- |
| HTML Standard # the-fieldset-element |

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

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

See also
--------

* The `<legend>` element
* The `<input>` element
* The `<label>` element
* The `<form>` element


<dialog>: The Dialog element - HTML: HyperText Markup Language

<dialog>: The Dialog element
============================

Baseline 2022
-------------

Newly availableSince March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`<dialog>`** HTML element represents a modal or non-modal dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.

The HTML `<dialog>` element is used to create both modal and non-modal dialog boxes. Modal dialog boxes interrupt interaction with the rest of the page being inert, while non-modal dialog boxes allow interaction with the rest of the page.

JavaScript should be used to display the `<dialog>` element. Use the `.showModal()` method to display a modal dialog and the `.show()` method to display a non-modal dialog. The dialog box can be closed using the `.close()` method or using the `dialog` method when submitting a `<form>` that is nested within the `<dialog>` element. Modal dialogs can also be closed by pressing the `Esc` key.

Attributes
----------

This element includes the global attributes.

**Warning:** The `tabindex` attribute must not be used on the `<dialog>` element. See usage notes.

`open`

 Indicates that the dialog box is active and is available for interaction. If the `open` attribute is not set, the dialog box will not be visible to the user.
 It is recommended to use the `.show()` or `.showModal()` method to render dialogs, rather than the `open` attribute. If a `<dialog>` is opened using the `open` attribute, it is non-modal.

**Note:** While you can toggle between the open and closed states of non-modal dialog boxes by toggling the presence of the `open` attribute, this approach is not recommended.

Usage notes
-----------

* HTML `<form>` elements can be used to close a dialog box if they have the attribute `method="dialog"` or if the button used to submit the form has `formmethod="dialog"` set. When a `<form>` within a `<dialog>` is submitted via the `dialog` method, the dialog box closes, the states of the form controls are saved but not submitted, and the `returnValue` property gets set to the value of the button that was activated.
* The CSS `::backdrop` pseudo-element can be used to style the backdrop of a modal dialog, which is displayed behind the `<dialog>` element when the dialog is displayed using the `HTMLDialogElement.showModal()` method. For example, this pseudo-element could be used to blur, darken, or otherwise obfuscate the inert content behind the modal dialog.
* The `autofocus` attribute should be added to the element the user is expected to interact with immediately upon opening a modal dialog. If no other element involves more immediate interaction, it is recommended to add `autofocus` to the close button inside the dialog, or the dialog itself if the user is expected to click/activate it to dismiss.
* Do not add the `tabindex` property to the `<dialog>` element as it is not interactive and does not receive focus. The dialog's contents, including the close button contained in the dialog, can receive focus and be interactive.
Examples
--------

### HTML-only dialog

This example demonstrates the create a non-modal dialog by using only HTML. Because of the boolean `open` attribute in the `<dialog>` element, the dialog appears open when the page loads. The dialog can be closed by clicking the "OK" button because the `method` attribute in the `<form>` element is set to `"dialog"`. In this case, no JavaScript is needed to close the form.

```html
<dialog open>
  <p>Greetings, one and all!</p>
  <form method="dialog">
    <button>OK</button>
  </form>
</dialog>
```

#### Result

**Note:** Reload the page to reset the output.

This dialog is initially open because of the presence of the `open` attribute. Dialogs that are displayed using the `open` attribute are non-modal. After clicking "OK", the dialog gets dismissed, leaving the Result frame empty. When the dialog is dismissed, there is no method provided to reopen it. For this reason, the preferred method to display non-modal dialogs is by using the `HTMLDialogElement.show()` method. It is possible to toggle the display of the dialog by adding or removing the boolean `open` attribute, but it is not the recommended practice.

### Creating a modal dialog

This example demonstrates a modal dialog with a gradient backdrop. The `.showModal()` method opens the modal dialog when the "Show the dialog" button is activated. The dialog can be closed by pressing the `Esc` key or via the `close()` method when the "Close" button within the dialog is activated.

When a dialog opens, the browser, by default, gives focus to the first element that can be focused within the dialog. In this example, the `autofocus` attribute is applied to the "Close" button, giving it focus when the dialog opens, as this is the element we expect the user will interact with immediately after the dialog opens.

#### HTML

```html
<dialog>
  <button autofocus>Close</button>
  <p>This modal dialog has a groovy backdrop!</p>
</dialog>
<button>Show the dialog</button>
```

#### CSS

We can style the backdrop of the dialog by using the `::backdrop` pseudo-element.

```css
::backdrop {
  background-image: linear-gradient(
    45deg,
    magenta,
    rebeccapurple,
    dodgerblue,
    green
  );
  opacity: 0.75;
}
```

#### JavaScript

The dialog is opened modally using the `.showModal()` method and closed using the `.close()` method.

```js
const dialog = document.querySelector("dialog");
const showButton = document.querySelector("dialog + button");
const closeButton = document.querySelector("dialog button");

// "Show the dialog" button opens the dialog modally
showButton.addEventListener("click", () => {
  dialog.showModal();
});

// "Close" button closes the dialog
closeButton.addEventListener("click", () => {
  dialog.close();
});
```

#### Result

When the modal dialog is displayed, it appears above any other dialogs that might be present. Everything outside the modal dialog is inert and interactions outside the dialog are blocked. Notice that when the dialog is open, with the exception of the dialog itself, interaction with the document is not possible; the "Show the dialog" button is mostly obfuscated by the almost opaque backdrop of the dialog and is inert.

### Handling the return value from the dialog

This example demonstrates the `returnValue` of the `<dialog>` element and how to close a modal dialog by using a form. By default, the `returnValue` is the empty string or the value of the button that submits the form within the `<dialog>` element, if there is one.

This example opens a modal dialog when the "Show the dialog" button is activated. The dialog contains a form with a `<select>` and two `<button>` elements, which default to `type="submit"`. An event listener updates the value of the "Confirm" button when the select option changes. If the "Confirm" button is activated to close the dialog, the current value of the button is the return value. If the dialog is closed by pressing the "Cancel" button, the `returnValue` is `cancel`.

When the dialog is closed, the return value is displayed under the "Show the dialog" button. If the dialog is closed by pressing the `Esc` key, the `returnValue` is not updated, and the `close` event doesn't occur, so the text in the `<output>` is not updated.

#### HTML

```html
<!-- A modal dialog containing a form -->
<dialog id="favDialog">
  <form>
    <p>
      <label>
        Favorite animal:
        <select>
          <option value="default">Choose…</option>
          <option>Brine shrimp</option>
          <option>Red panda</option>
          <option>Spider monkey</option>
        </select>
      </label>
    </p>
    <div>
      <button value="cancel" formmethod="dialog">Cancel</button>
      <button id="confirmBtn" value="default">Confirm</button>
    </div>
  </form>
</dialog>
<p>
  <button id="showDialog">Show the dialog</button>
</p>
<output></output>
```

#### JavaScript

```js
const showButton = document.getElementById("showDialog");
const favDialog = document.getElementById("favDialog");
const outputBox = document.querySelector("output");
const selectEl = favDialog.querySelector("select");
const confirmBtn = favDialog.querySelector("#confirmBtn");

// "Show the dialog" button opens the <dialog> modally
showButton.addEventListener("click", () => {
  favDialog.showModal();
});

// "Favorite animal" input sets the value of the submit button
selectEl.addEventListener("change", (e) => {
  confirmBtn.value = selectEl.value;
});

// "Cancel" button closes the dialog without submitting because of [formmethod="dialog"], triggering a close event.
favDialog.addEventListener("close", (e) => {
  outputBox.value =
    favDialog.returnValue === "default"
      ? "No return value."
      : `ReturnValue: ${favDialog.returnValue}.`; // Have to check for "default" rather than empty string
});

// Prevent the "confirm" button from the default behavior of submitting the form, and close the dialog with the `close()` method, which triggers the "close" event.
confirmBtn.addEventListener("click", (event) => {
  event.preventDefault(); // We don't want to submit this fake form
  favDialog.close(selectEl.value); // Have to send the select box value here.
});
```

#### Result

The above examples demonstrate the following three methods of closing modal dialogs:

* By submitting the form within the dialog form using the `dialog` method (as seen in the HTML-only example).
* By pressing the `Esc` key.
* By calling the `HTMLDialogElement.close()` method (as seen in the modal example).
 In this example, the "Cancel" button closes the dialog via the `dialog` form method and the "Confirm" button closes the dialog via the `HTMLDialogElement.close()` method.

The "Cancel" button includes the `formmethod="dialog"` attribute, which overrides the `<form>`'s default `GET` method. When a form's method is `dialog`, the state of the form is saved but not submitted, and the dialog gets closed.

Without an `action`, submitting the form via the default `GET` method causes a page to reload. We use JavaScript to prevent the submission and close the dialog with the `event.preventDefault()` and `HTMLDialogElement.close()` methods, respectively.

It is important to provide a closing mechanism within every `dialog` element. The `Esc` key does not close non-modal dialogs by default, nor can one assume that a user will even have access to a physical keyboard (e.g., someone using a touch screen device without access to a keyboard).

### Closing a dialog with a required form input

When a form inside a dialog has a required input, the user agent will only let you close the dialog once you provide a value for the required input. To close such dialog, either use the `formnovalidate` attribute on the close button or call the `close()` method on the dialog object when the close button is clicked.

```html
<dialog id="dialog">
  <form method="dialog">
    <p>
      <label>
        Favorite animal:
        <input type="text" required />
      </label>
    </p>
    <div>
      <input type="submit" id="normal-close" value="Normal close" />
      <input
 type="submit"
 id="novalidate-close"
 value="Novalidate close"
 formnovalidate />
      <input type="submit" id="js-close" value="JS close" />
    </div>
  </form>
</dialog>
<p>
  <button id="show-dialog">Show the dialog</button>
</p>
<output></output>
```

```
[type="submit"] {
  margin-right: 1rem;
}
```

#### JavaScript

```js
const showBtn = document.getElementById("show-dialog");
const dialog = document.getElementById("dialog");
const jsCloseBtn = dialog.querySelector("#js-close");

showBtn.addEventListener("click", () => {
  dialog.showModal();
});

jsCloseBtn.addEventListener("click", (e) => {
  e.preventDefault();
  dialog.close();
});
```

#### Result

From the output, we see it is impossible to close the dialog using the *Normal close* button. But the dialog can be closed if we bypass the form validation using the `formnovalidate` attribute on the *Cancel* button. Programmatically, `dialog.close()` will also close such dialog.

### Animating dialogs

`<dialog>`s are set to `display: none;` when hidden and `display: block;` when shown, as well as being removed from / added to the top layer and the accessibility tree. Therefore, for `<dialog>` elements to be animated the `display` property needs to be animatable. Supporting browsers animate `display` with a variation on the discrete animation type. Specifically, the browser will flip between `none` and another value of `display` so that the animated content is shown for the entire animation duration.

So for example:

* When animating `display` from `none` to `block` (or another visible `display` value), the value will flip to `block` at `0%` of the animation duration so it is visible throughout.
* When animating `display` from `block` (or another visible `display` value) to `none`, the value will flip to `none` at `100%` of the animation duration so it is visible throughout.

**Note:** When animating using CSS transitions, `transition-behavior: allow-discrete` needs to be set to enable the above behavior. This behavior is available by default when animating with CSS animations; an equivalent step is not required.

#### Transitioning dialog elements

When animating `<dialog>`s with CSS transitions, the following features are required:

`@starting-style` at-rule

Provides a set of starting values for properties set on the `<dialog>` that you want to transition from every time it is opened. This is needed to avoid unexpected behavior. By default, CSS transitions only occur when a property changes from one value to another on a visible element; they are not triggered on elements' first style updates, or when the `display` type changes from `none` to another type.

`display` property

Add `display` to the transitions list so that the `<dialog>` will remain as `display: block` (or another visible `display` value set on the dialog's open state) for the duration of the transition, ensuring the other transitions are visible.

`overlay` property

Include `overlay` in the transitions list to ensure the removal of the `<dialog>` from the top layer is deferred until the transition completes, again ensuring the transition is visible.

`transition-behavior` property

Set `transition-behavior: allow-discrete` on the `display` and `overlay` transitions (or on the `transition` shorthand) to enable discrete transitions on these two properties that are not by default animatable.

Here is a quick example to show what this might look like.

##### HTML

The HTML contains a `<dialog>` element, plus a button to show the dialog. Additionally, the `<dialog>` element contains another button to close itself.

```html
<dialog id="dialog">
  Content here
  <button class="close">close</button>
</dialog>

<button class="show">Show Modal</button>
```

##### CSS

In the CSS, we include a `@starting-style` block that defines the transition starting styles for the `opacity` and `transform` properties, transition end styles on the `dialog[open]` state, and default styles on the default `dialog` state to transition back to once the `<dialog>` has appeared. Note how the `<dialog>`'s `transition` list includes not only these properties, but also the `display` and `overlay` properties, each with `allow-discrete` set on them.

We also set a starting style value for the `background-color` property on the `::backdrop` that appears behind the `<dialog>` when it opens, to provide a nice darkening animation. The `dialog[open]::backdrop` selector selects only the backdrops of `<dialog>` elements when the dialog is open.

```css
/\* Open state of the dialog \*/
dialog[open] {
  opacity: 1;
  transform: scaleY(1);
}

/\* Closed state of the dialog \*/
dialog {
  opacity: 0;
  transform: scaleY(0);
  transition:
    opacity 0.7s ease-out,
    transform 0.7s ease-out,
    overlay 0.7s ease-out allow-discrete,
    display 0.7s ease-out allow-discrete;
  /\* Equivalent to
 transition: all 0.7s allow-discrete; \*/
}

/\* Before-open state \*/
/\* Needs to be after the previous dialog[open] rule to take effect,
 as the specificity is the same \*/
@starting-style {
  dialog[open] {
    opacity: 0;
    transform: scaleY(0);
  }
}

/\* Transition the :backdrop when the dialog modal is promoted to the top layer \*/
dialog::backdrop {
  background-color: rgb(0 0 0 / 0%);
  transition:
    display 0.7s allow-discrete,
    overlay 0.7s allow-discrete,
    background-color 0.7s;
  /\* Equivalent to
 transition: all 0.7s allow-discrete; \*/
}

dialog[open]::backdrop {
  background-color: rgb(0 0 0 / 25%);
}

/\* This starting-style rule cannot be nested inside the above selector
because the nesting selector cannot represent pseudo-elements. \*/

@starting-style {
  dialog[open]::backdrop {
    background-color: rgb(0 0 0 / 0%);
  }
}
```

##### JavaScript

The JavaScript adds event handlers to the show and close buttons causing them to show and close the `<dialog>` when they are clicked:

```js
const dialogElem = document.getElementById("dialog");
const showBtn = document.querySelector(".show");
const closeBtn = document.querySelector(".close");

showBtn.addEventListener("click", () => {
  dialogElem.showModal();
});

closeBtn.addEventListener("click", () => {
  dialogElem.close();
});
```

##### Result

The code renders as follows:

**Note:** Because `<dialog>`s change from `display: none` to `display: block` each time they are shown, the `<dialog>` transitions from its `@starting-style` styles to its `dialog[open]` styles every time the entry transition occurs. When the `<dialog>` closes, it transitions from its `dialog[open]` state to the default `dialog` state.

It is possible for the style transition on entry and exit to be different in such cases. See our Demonstration of when starting styles are used example for a proof of this.

#### dialog keyframe animations

When animating a `<dialog>` with CSS keyframe animations, there are some differences to note from transitions:

* You don't provide a `@starting-style`.
* You include the `display` value in a keyframe; this will be the `display` value for the entirety of the animation, or until another non-`none` display value is encountered.
* You don't need to explicitly enable discrete animations; there is no equivalent to `allow-discrete` inside keyframes.
* You don't need to set `overlay` inside keyframes either; the `display` animation handles the animation of the `<dialog>` from shown to hidden.

Let's have a look at an example so you can see what this looks like.

##### HTML

First, the HTML contains a `<dialog>` element, plus a button to show the dialog. Additionally, the `<dialog>` element contains another button to close itself.

```html
<dialog id="dialog">
  Content here
  <button class="close">close</button>
</dialog>

<button class="show">Show Modal</button>
```

##### CSS

The CSS defines keyframes to animate between the closed and shown states of the `<dialog>`, plus the fade-in animation for the `<dialog>`'s backdrop. The `<dialog>` animations include animating `display` to make sure the actual visible animation effects remain visible for the whole duration. Note that it wasn't possible to animate the backdrop fade out — the backdrop is immediately removed from the DOM when the `<dialog>` is closed, so there is nothing to animate.

```css
dialog {
  animation: fade-out 0.7s ease-out;
}

dialog[open] {
  animation: fade-in 0.7s ease-out;
}

dialog[open]::backdrop {
  animation: backdrop-fade-in 0.7s ease-out forwards;
}

/\* Animation keyframes \*/

@keyframes fade-in {
  0% {
    opacity: 0;
    transform: scaleY(0);
    display: none;
  }

  100% {
    opacity: 1;
    transform: scaleY(1);
    display: block;
  }
}

@keyframes fade-out {
  0% {
    opacity: 1;
    transform: scaleY(1);
    display: block;
  }

  100% {
    opacity: 0;
    transform: scaleY(0);
    display: none;
  }
}

@keyframes backdrop-fade-in {
  0% {
    background-color: rgb(0 0 0 / 0%);
  }

  100% {
    background-color: rgb(0 0 0 / 25%);
  }
}

body,
button {
  font-family: system-ui;
}
```

##### JavaScript

Finally, the JavaScript adds event handlers to the buttons to enable showing and closing the `<dialog>`:

```js
const dialogElem = document.getElementById("dialog");
const showBtn = document.querySelector(".show");
const closeBtn = document.querySelector(".close");

showBtn.addEventListener("click", () => {
  dialogElem.showModal();
});

closeBtn.addEventListener("click", () => {
  dialogElem.close();
});
```

##### Result

The code renders as follows:

Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Flow content,
 sectioning root |
| Permitted content | Flow content |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 Any element that accepts
 flow content |
| Implicit ARIA role | dialog |
| Permitted ARIA roles | `alertdialog` |
| DOM interface | `HTMLDialogElement` |

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

When implementing a dialog, it is important to consider the most appropriate place to set user focus. When using `HTMLDialogElement.showModal()` to open a `<dialog>`, focus is set on the first nested focusable element. Explicitly indicating the initial focus placement by using the `autofocus` attribute will help ensure initial focus is set on the element deemed the best initial focus placement for any particular dialog. When in doubt, as it may not always be known where initial focus could be set within a dialog, particularly for instances where a dialog's content is dynamically rendered when invoked, the `<dialog>` element itself may provide the best initial focus placement.

Ensure a mechanism is provided to allow users to close the dialog. The most robust way to ensure that all users can close the dialog is to include an explicit button to do so, such as a confirmation, cancellation, or close button.

By default, a dialog invoked by the `showModal()` method can be dismissed by pressing the `Esc` key. A non-modal dialog does not dismiss via the `Esc` key by default, and depending on what the non-modal dialog represents, it may not be desired for this behavior. Keyboard users expect the `Esc` key to close modal dialogs; ensure that this behavior is implemented and maintained. If multiple modal dialogs are open, pressing the `Esc` key should close only the last shown dialog. When using `<dialog>`, this behavior is provided by the browser.

While dialogs can be created using other elements, the native `<dialog>` element provides usability and accessibility features that must be replicated if you use other elements for a similar purpose. If you're creating a custom dialog implementation, ensure that all expected default behaviors are supported and proper labeling recommendations are followed.

The `<dialog>` element is exposed by browsers in a manner similar to custom dialogs that use the ARIA role="dialog" attribute. `<dialog>` elements invoked by the `showModal()` method implicitly have aria-modal="true", whereas `<dialog>` elements invoked by the `show()` method or displayed using the `open` attribute or by changing the default `display` of a `<dialog>` are exposed as `[aria-modal="false"]`. When implementing modal dialogs, everything other than the `<dialog>` and its contents should be rendered inert using the `inert` attribute. When using `<dialog>` along with the `HTMLDialogElement.showModal()` method, this behavior is provided by the browser.

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

| Specification |
| --- |
| HTML Standard # the-dialog-element |

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

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

See also
--------

* `HTMLDialogElement` interface
* `close` event
* `cancel` event
* `open` property of the `HTMLDialogElement` interface
* `inert` global attribute for HTML elements
* `::backdrop` CSS pseudo-element
* Web forms in the Learn area


<dl>: The Description List element - HTML: HyperText Markup Language

<dl>: The Description List element
==================================

The **`<dl>`** HTML element represents a description list. The element encloses a list of groups of terms (specified using the `<dt>` element) and descriptions (provided by `<dd>` elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs).

Try it
------

|  |  |
| --- | --- |
| Content categories | Flow content, and if the `<dl>` element's children include one
 name-value group, palpable content.
  |
| Permitted content |
 Either: Zero or more groups each consisting of one or more
 `<dt>` elements followed by one or more
 `<dd>` elements, optionally intermixed with
 `<script>` and
 `<template>` elements.Or: (in
 WHATWG HTML, W3C HTML 5.2
 and later) One or more `<div>` elements,
 optionally intermixed with `<script>` and
 `<template>` elements.
  |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 Any element that accepts
 flow content.
  |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | `group`,
 `list`, `none`, `presentation` |
| DOM interface | `HTMLDListElement` |

Attributes
----------

This element only includes the 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

### 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

### 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

### 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

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 HTML allows wrapping each name-value group in a `<dl>` element in a `<div>` element. This can be useful when using microdata, or when 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

Notes
-----

Do not use this element (nor `<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 `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
* Brief Note on Description List Support
Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-dl-element |

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

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

See also
--------

* `<dt>`
* `<dd>`


<cite>: The Citation element - HTML: HyperText Markup Language

<cite>: The Citation element
============================

The **`<cite>`** HTML element is used to mark up the title of a cited creative work. The reference may be in an abbreviated form according to context-appropriate conventions related to citation metadata.

Try it
------

Attributes
----------

This element only includes the global attributes.

Usage notes
-----------

In the context of the `<cite>` element, a creative work that might be cited could be, for example, one of the following:

* A book
* A research paper
* An essay
* A poem
* A musical score
* A song
* A play or film script
* A film
* A television show
* A game
* A sculpture
* A painting
* A theatrical production
* A play
* An opera
* A musical
* An exhibition
* A legal case report
* A computer program
* A website
* A web page
* A blog post or comment
* A forum post or comment
* A tweet
* A Facebook post
* A written or oral statement
* And so forth.

To include a reference to the source of quoted material which is contained within a `<blockquote>` or `<q>` element, use the `cite` attribute on the element.

Typically, browsers style the contents of a `<cite>` element in italics by default. To avoid this, apply the CSS `font-style` property to the `<cite>` element.

Examples
--------

```html
<p>More information can be found in <cite>[ISO-0000]</cite>.</p>
```

### Result

Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Flow content,
 phrasing content, palpable content.
  |
| Permitted content | Phrasing content. |
| Tag omission | None, both the starting and ending tag are mandatory. |
| Permitted parents |
 Any element that accepts
 phrasing content.
  |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | Any |
| DOM interface | `HTMLElement` Up to Gecko 1.9.2 (Firefox 4)
 inclusive, Firefox implements the
 `HTMLSpanElement` interface for this element.
  |

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

| Specification |
| --- |
| HTML Standard # the-cite-element |

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

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

See also
--------

* The element `<blockquote>` for long quotations.
* The element `<q>` for inline quotations and the `cite` attribute.


<style>: The Style Information element - HTML: HyperText Markup Language

<style>: The Style Information element
======================================

The **`<style>`** 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.

Try it
------

The `<style>` element must be included inside the `<head>` of the document. In general, it is better to put your styles in external stylesheets and apply them using `<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, 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.

`blocking`
Experimental

This attribute explicitly indicates that certain operations should be blocked on the fetching of critical subresources. `@import`-ed stylesheets are generally considered as critical subresources, whereas `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, 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. 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 sets.

### Deprecated attributes

`type`
Deprecated

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

### 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.

```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

### 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

Technical summary
-----------------

|  |  |
| --- | --- |
| Content categories | Metadata content, and if the `scoped` attribute is present:
 flow content.
  |
| Permitted content |
 Text content matching the `type` attribute, that is
 `text/css`.
  |
| Tag omission | Neither tag is omissible. |
| Permitted parents |
 Any element that accepts
 metadata content.
  |
| Implicit ARIA role | No corresponding role |
| Permitted ARIA roles | No `role` permitted |
| DOM interface | `HTMLStyleElement` |

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

| Specification |
| --- |
| HTML Standard # the-style-element |

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

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

See also
--------

* The `<link>` element, which allows us to apply external stylesheets to a document.
* Alternative Style Sheets