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/performance
data/mdn-content/files/en-us/web/performance/fundamentals/index.md
--- title: Performance fundamentals slug: Web/Performance/Fundamentals page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} Performance means efficiency. In the context of Open Web Apps, this document explains in general what performance is, how the browser platform helps improve it, and what tools and processes you can use to test and improve it. ## What is performance? Ultimately, user-perceived performance is the only performance that matters. Users provide inputs to the system through touch, movement, and speech. In return, they perceive outputs through sight, touch, and hearing. Performance is the quality of system outputs in response to user inputs. All other things being equal, code optimized for some target besides user-perceived performance (hereafter UPP) loses when competing against code optimized for UPP. Users prefer, say, a responsive, smooth app that only processes 1,000 database transactions per second, over a choppy, unresponsive app that processes 100,000,000 per second. Of course, it's by no means pointless to optimize other metrics, but real UPP targets come first. The next few subsections point out and discuss essential performance metrics. ### Responsiveness Responsiveness means how fast the system provides outputs (possibly multiple ones) in response to user inputs. For example, when a user taps the screen, they expect the pixels to change in a certain way. For this interaction, the responsiveness metric is the time elapsed between the tap and the pixel change. Responsiveness sometimes involves multiple stages of feedback. Application launch is one particularly important case discussed in more detail below. Responsiveness is important because people get frustrated and angry when they're ignored. Your app is ignoring the user every second that it fails to respond to the user's input. ### Frame rate Frame rate is the rate at which the system changes pixels displayed to the user. This is a familiar concept: everyone prefers, say, games that display 60 frames per second over ones that display 10 frames per second, even if they can't explain why. Frame rate is important as a "quality of service" metric. Computer displays are designed to "fool" user's eyes, by delivering photons to them that mimic reality. For example, paper covered with printed text reflects photons to the user's eyes in some pattern. By manipulating pixels, a reader app emits photons in a similar pattern to "fool" the user's eyes. As your brain infers, motion is not jerky and discrete, but rather "updates" smoothly and continuously. (Strobe lights are fun because they turn that upside down, starving your brain of inputs to create the illusion of discrete reality). On a computer display, a higher frame rate makes for a more faithful imitation of reality. > **Note:** Humans usually cannot perceive differences in frame rate above 60Hz. That's why most modern electronic displays are designed to refresh at that rate. A television probably looks choppy and unrealistic to a hummingbird, for example. ### Memory usage **Memory usage** is another key metric. Unlike responsiveness and frame rate, users don't directly perceive memory usage, but memory usage closely approximates "user state". An ideal system would maintain 100% of user state at all times: all applications in the system would run simultaneously, and all applications would retain the state created by the user the last time the user interacted with the application (application state is stored in computer memory, which is why the approximation is close). From this comes an important but counter-intuitive corollary: a well-designed system does not maximize the amount of **free** memory. Memory is a resource, and free memory is an unused resource. Rather, a well-designed system has been optimized to **use** as much memory as possible to maintain user state, while meeting other UPP goals. That doesn't mean the system should **waste** memory. When a system uses more memory than necessary to maintain some particular user state, the system is wasting a resource it could use to retain some other user state. In practice, no system can maintain all user states. Intelligently allocating memory to user state is an important concern that we go over in more detail below. ### Power usage The final metric discussed here is **power usage**. Like memory usage, users perceive power usage only indirectly, by how long their devices can maintain all other UPP goals. In service of meeting UPP goals, the system must use only the minimum power required. The remainder of this document will discuss performance in terms of these metrics. ## Platform performance optimizations This section provides a brief overview of how Firefox/Gecko contributes to performance generally, below the level of all applications. From a developer's or user's perspective, this answers the question, "What does the platform do for you?" ### Web technologies The Web platform provides many tools, some better suited for particular jobs than others. All application logic is written in JavaScript. To display graphics, developers can use HTML or CSS (i.e. high-level declarative languages), or use low-level imperative interfaces offered by the {{ htmlelement("canvas") }} element (which includes [WebGL](/en-US/docs/Web/API/WebGL_API)). Somewhere "in between" HTML/CSS and Canvas is [SVG](/en-US/docs/Web/SVG), which offers some benefits of both. HTML and CSS greatly increase productivity, sometimes at the expense of frame rate or pixel-level control over rendering. Text and images reflow automatically, UI elements automatically receive the system theme, and the system provides "built-in" support for some use cases developers may not think of initially, like different-resolution displays or right-to-left languages. The `canvas` element offers a pixel buffer directly for developers to draw on. This gives developers pixel-level control over rendering and precise control of frame rate, but now the developers need to deal with multiple resolutions and orientations, right-to-left languages, and so forth. Developers draw to canvases using either a familiar 2D drawing API, or WebGL, a "close to the metal" binding that mostly follows OpenGL ES 2.0. ### Gecko rendering The Gecko JavaScript engine supports just-in-time (JIT) compilation. This enables application logic to perform comparably to other virtual machines — such as Java virtual machines — and in some cases even close to "native code". The graphics pipeline in Gecko that underpins HTML, CSS, and Canvas is optimized in several ways. The HTML/CSS layout and graphics code in Gecko reduces invalidation and repainting for common cases like scrolling; developers get this support "for free". Pixel buffers painted by both Gecko "automatically" and applications to `canvas` "manually" minimize copies when being drawn to the display framebuffer. This is done by avoiding intermediate surfaces where they would create overhead (such as per-application "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware. Complex scenes are rendered using the device's GPU for maximum performance. To improve power usage, simple scenes are rendered using special dedicated composition hardware, while the GPU idles or turns off. Fully static content is the exception rather than the rule for rich applications. Rich applications use dynamic content with {{ cssxref("animation") }} and {{ cssxref("transition") }} effects. Transitions and animations are particularly important to applications: developers can use CSS to declare complicated behavior with a simple, high-level syntax. In turn, Gecko's graphics pipeline is highly optimized to render common animations efficiently. Common-case animations are "offloaded" to the system compositor, which can render them in a performant, power-efficient fashion. An app's startup performance matters just as much as its runtime performance. Gecko is optimized to load a wide variety of content efficiently: the entire Web! Many years of improvements targeting this content, like parallel HTML parsing, intelligent scheduling of reflows and image decoding, clever layout algorithms, etc., translate just as well to improving Web applications on Firefox. ## Application performance This section is intended for developers asking the question: "How can I make my app fast"? ### Startup performance Application startup is punctuated by three user-perceived events, generally speaking: - The first is the application **first paint** — the point at which sufficient application resources have been loaded to paint an initial frame - The second is when the application becomes **interactive** — for example, users are able to tap a button and the application responds - The final event is **full load** — for example when all the user's albums have been listed in a music player The key to fast startup is to keep two things in mind: UPP is all that matters, and there's a "critical path" to each user-perceived event above. The critical path is exactly and only the code that must run to produce the event. For example, to paint an application's first frame that comprises visually some HTML and CSS to style that HTML: 1. The HTML must be parsed 2. The DOM for that HTML must be constructed 3. Resources like images in that part of the DOM have to be loaded and decoded 4. The CSS styles must be applied to that DOM 5. The styled document has to be reflowed Nowhere in that list is "load the JS file needed for an uncommon menu"; "fetch and decode the image for the High Scores list", etc. Those work items are not on the critical path to painting the first frame. It seems obvious, but to reach a user-perceived startup event more quickly, the main "trick" is run _only the code on the critical path._ Shorten the critical path by simplifying the scene. The Web platform is highly dynamic. JavaScript is a dynamically-typed language, and the Web platform allows loading code, HTML, CSS, images, and other resources dynamically. These features can be used to defer work that's off the critical path by loading unnecessary content "lazily" some time after startup. Another problem that can delay startup is idle time, caused by waiting for responses to requests (like database loads). To avoid this problem, applications should issue requests as early as possible in startup (this is called "front-loading"). Then when the data is needed later, hopefully it's already available and the application doesn't have to wait. > **Note:** For much more information on improving startup performance, read [Optimizing startup performance](/en-US/docs/Web/Performance/Optimizing_startup_performance). On the same note, notice that locally-cached, static resources can be loaded much faster than dynamic data fetched over high-latency, low-bandwidth mobile networks. Network requests should never be on the critical path to early application startup. Local caching/offline apps can be achieved via [Service Workers](/en-US/docs/Web/API/Service_Worker_API). See [Offline and background operation](/en-US/docs/Web/Progressive_web_apps/Guides/Offline_and_background_operation) for a guide about using service workers for offline and background sync capabilities. ### Frame rate The first important thing for high frame rate is to choose the right tool. Use HTML and CSS to implement content that's mostly static, scrolled, and infrequently animated. Use Canvas to implement highly dynamic content, like games that need tight control over rendering and don't need theming. For content drawn using Canvas, it's up to the developer to hit frame rate targets: they have direct control over what's drawn. For HTML and CSS content, the path to high frame rate is to use the right primitives. Firefox is highly optimized to scroll arbitrary content; this is usually not a concern. But often trading some generality and quality for speed, such as using a static rendering instead of a CSS radial gradient, can push scrolling frame rate over a target. CSS [media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) allow these compromises to be restricted only to devices that need them. Many applications use transitions or animations through "pages", or "panels". For example, the user taps a "Settings" button to transition into an application configuration screen, or a settings menu "pops up". Firefox is highly optimized to transition and animate scenes that: - use pages/panels approximately the size of the device screen or smaller - transition/animate the CSS `transform` and `opacity` properties Transitions and animations that adhere to these guidelines can be offloaded to the system compositor and run maximally efficiently. ### Memory and power usage Improving memory and power usage is a similar problem to speeding up startup: don't do unneeded work or lazily load uncommonly-used UI resources. Do use efficient data structures and ensure resources like images are optimized well. Modern CPUs can enter a lower-power mode when mostly idle. Applications that constantly fire timers or keep unnecessary animations running prevent CPUs from entering low-power mode. Power-efficient applications shouldn't do that. When applications are sent to the background, a {{domxref("document.visibilitychange_event", "visibilitychange")}} event is fired on their documents. This event is a developer's friend; applications should listen for it. ### Specific coding tips for application performance The following practical tips will help improve one or more of the Application performance factors discussed above. #### Use CSS animations and transitions Instead of using some library's `animate()` function, which probably currently uses many badly performing technologies ({{domxref("setTimeout()")}} or `top`/`left` positioning, for example) use [CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations). In many cases, you can actually use [CSS Transitions](/en-US/docs/Web/CSS/CSS_transitions/Using_CSS_transitions) to get the job done. This works well because the browser is designed to optimize these effects and use the GPU to handle them smoothly with minimal impact on processor performance. Another benefit is that you can define these effects in CSS along with the rest of your app's look-and-feel, using a standardized syntax. CSS animations give you very granular control over your effects using [keyframes](/en-US/docs/Web/CSS/@keyframes), and you can even watch events fired during the animation process in order to handle other tasks that need to be performed at set points in the animation process. You can easily trigger these animations with the {{cssxref(":hover")}}, {{cssxref(":focus")}}, or {{cssxref(":target")}}, or by dynamically adding and removing classes on parent elements. If you want to create animations on the fly or modify them in [JavaScript](/en-US/docs/Web/JavaScript), James Long has written a simple library for that called [CSS-animations.js](https://github.com/jlongster/css-animations.js/). #### Use CSS transforms Instead of tweaking absolute positioning and fiddling with all that math yourself, use the {{cssxref("transform")}} CSS property to adjust the position, scale, and so forth of your content. Alternatively, you can use the individual transformation properties of {{cssxref("translate")}}, {{cssxref("scale")}}, and {{cssxref("rotate")}}. The reason is, once again, hardware acceleration. The browser can do these tasks on your GPU, letting the CPU handle other things. In addition, transforms give you capabilities you might not otherwise have. Not only can you translate elements in 2D space, but you can transform in three dimensions, skew and rotate, and so forth. Paul Irish has an [in-depth analysis of the benefits of `translate()`](https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/) (2012) from a performance point of view. In general, however, you have the same benefits you get from using CSS animations: you use the right tool for the job and leave the optimization to the browser. You also use an easily extensible way of positioning elements — something that needs a lot of extra code if you simulate translation with `top` and `left` positioning. Another bonus is that this is just like working in a `canvas` element. > **Note:** You may need to attach a `translateZ(0.1)` transform if you wish to get hardware acceleration on your CSS animations, depending on platform. As noted above, this can improve performance. When overused, it can have memory consumption issues. What you do in this regard is up to you — do some testing and find out what's best for your particular app. #### Use `requestAnimationFrame()` instead of `setInterval()` Calls to {{domxref("setInterval()")}} run code at a presumed frame rate that may or may not be possible under current circumstances. It tells the browser to render results even while the browser isn't actually drawing; that is, while the video hardware hasn't reached the next display cycle. This wastes processor time and can even lead to reduced battery life on the user's device. Instead, you should try to use {{domxref("window.requestAnimationFrame()")}}. This waits until the browser is actually ready to start building the next frame of your animation, and won't bother if the hardware isn't going to actually draw anything. Another benefit to this API is that animations won't run while your app isn't visible on the screen (such as if it's in the background and some other task is operating). This will save battery life and prevent users from cursing your name into the night sky. #### Make events immediate As old-school, accessibility-aware Web developers we love click events since they also support keyboard input. On mobile devices, these are too slow. You should use {{domxref("Element/touchstart_event", "touchstart")}} and {{domxref("Element/touchend_event", "touchend")}} instead. The reason is that these don't have a delay that makes the interaction with the app appear sluggish. If you test for touch support first, you don't sacrifice accessibility, either. For example, the Financial Times uses a library called [fastclick](https://github.com/ftlabs/fastclick) for that purpose, which is available for you to use. #### Keep your interface simple One big performance issue we found in HTML apps was that moving lots of [DOM](/en-US/docs/Web/API/Document_Object_Model) elements around makes everything sluggish — especially when they feature lots of gradients and drop shadows. It helps a lot to simplify your look-and-feel and move a proxy element around when you drag and drop. When, for example, you have a long list of elements (let's say tweets), don't move them all. Instead, keep in your DOM tree only the ones that are visible and a few on either side of the currently visible set of tweets. Hide or remove the rest. Keeping the data in a JavaScript object instead of accessing the DOM can vastly improve your app's performance. Think of the display as a presentation of your data rather than the data itself. That doesn't mean you can't use straight HTML as the source; just read it once and then scroll 10 elements, changing the content of the first and last accordingly to your position in the results list, instead of moving 100 elements that aren't visible. The same trick applies in games to sprites: if they aren't currently on the screen, there is no need to poll them. Instead, re-use elements that scroll off-screen as new ones coming in. ## General application performance analysis Firefox, Chrome, and other browsers include built-in tools that can help you diagnose slow page rendering. In particular, [Firefox's Network Monitor](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/index.html) will display a precise timeline of when each network request on your page happens, how large it is, and how long it takes. ![The Firefox network monitor showing get requests, multiple files, and different times taken to load each resource on a graph.](network-monitor.jpg) If your page contains JavaScript code that is taking a long time to run, the [JavaScript profiler](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html) will pinpoint the slowest lines of code: ![The Firefox JavaScript profiler showing a completed profile 1.](javascript-profiler.png) The [Built-in Gecko Profiler](https://firefox-source-docs.mozilla.org/tools/profiler/index.html) is a very useful tool that provides even more detailed information about which parts of the browser code are running slowly while the profiler runs. This is a bit more complex to use, but provides a lot of useful details. ![A built-in Gecko profiler windows showing a lot of network information.](gecko-profiler.png) > **Note:** You can use these tools with the Android browser by running Firefox and enabling [about:debugging](https://firefox-source-docs.mozilla.org/devtools-user/about_colon_debugging/index.html). In particular, making dozens or hundreds of network requests takes longer in mobile browsers. Rendering large images and CSS gradients can also take longer. Downloading large files can take longer, even over a fast network, because mobile hardware is sometimes too slow to take advantage of all the available bandwidth. For useful general tips on mobile Web performance, have a look at Maximiliano Firtman's [Mobile Web High Performance](https://www.slideshare.net/firt/mobile-web-high-performance) talk. ### Test cases and submitting bugs If the Firefox and Chrome developer tools don't help you find a problem, or if they seem to indicate that the Web browser has caused the problem, try to provide a reduced test case that maximally isolates the problem. That often helps in diagnosing problems. See if you can reproduce the problem by saving and loading a static copy of an HTML page (including any images/stylesheets/scripts it embeds). If so, edit the static files to remove any private information, then send them to others for help (submit a [Bugzilla](https://bugzilla.mozilla.org/) report, for example, or host it on a server and share the URL). You should also share any profiling information you've collected using the tools listed above.
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/lazy_loading/index.md
--- title: Lazy loading slug: Web/Performance/Lazy_loading page-type: guide spec-urls: https://html.spec.whatwg.org/multipage/#lazy-loading-attributes --- {{QuickLinksWithSubPages("Web/Performance")}} **Lazy loading** is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. It's a way to shorten the length of the [critical rendering path](/en-US/docs/Web/Performance/Critical_rendering_path), which translates into reduced page load times. Lazy loading can occur on different moments in the application, but it typically happens on some user interactions such as scrolling and navigation. ## Overview As the web has evolved, we have come to see huge increases in the number and size of assets sent to users. Between 2011 and 2019, the median resource weight increased from **\~100KB** to **\~400KB** for desktop and **\~50KB** to **\~350KB** for mobile. While Image size has increased from **\~250KB** to **\~900KB** on desktop and **\~100KB** to **\~850KB** on mobile. One of the methods we can use to tackle this problem is to shorten the [Critical Rendering Path](/en-US/docs/Web/Performance/Critical_rendering_path) length by lazy loading resources that are not critical for the first render to happen. A practical example would be when you land on the home page of an e-commerce site with a link to a cart page/section, and none of the cart page's resources (such as JavaScript, CSS, and images) are downloaded **until** you navigate there. ## Strategies Lazy loading can be applied to multiple resources and through multiple strategies. ### General #### Code splitting JavaScript, CSS and HTML can be split into smaller chunks. This enables sending the minimal code required to provide value upfront, improving page-load times. The rest can be loaded on demand. - Entry point splitting: separates code by entry point(s) in the app - Dynamic splitting: separates code where [dynamic import()](/en-US/docs/Web/JavaScript/Reference/Operators/import) expressions are used ### JavaScript #### Script type module Any script tag with `type="module"` is treated as a [JavaScript module](/en-US/docs/Web/JavaScript/Guide/Modules) and is deferred by default. ### CSS By default, CSS is treated as a [render blocking](/en-US/docs/Web/Performance/Critical_rendering_path) resource, so the browser won't render any processed content until the [CSSOM](/en-US/docs/Web/API/CSS_Object_Model) is constructed. CSS must be thin, delivered as quickly as possible, and the usage media types and queries are advised to unblock rendering. ```html <link href="style.css" rel="stylesheet" media="all" /> <link href="portrait.css" rel="stylesheet" media="(orientation:portrait)" /> <link href="print.css" rel="stylesheet" media="print" /> ``` It is possible to perform some [CSS optimizations](/en-US/docs/Learn/Performance/CSS) to achieve that. ### Fonts By default, font requests are delayed until the render tree is constructed, which can result in delayed text rendering. It is possible to override the default behavior and preload web font resources using `<link rel="preload">`, the [CSS font-display property](/en-US/docs/Web/CSS/@font-face/font-display), and the [Font Loading API](/en-US/docs/Web/API/CSS_Font_Loading_API). See also: [Element Link](/en-US/docs/Web/HTML/Element/link). ### Images and iframes Very often, webpages contain many images that contribute to data-usage and how fast a page can load. Most of those images are off-screen ([non-critical](/en-US/docs/Web/Performance/Critical_rendering_path)), requiring a user interaction, like scrolling, in order to view them. #### Loading attribute The [`loading`](/en-US/docs/Web/HTML/Element/img#loading) attribute on an {{HTMLElement("img")}} element, or the [`loading`](/en-US/docs/Web/HTML/Element/iframe#loading) attribute on an {{HTMLElement("iframe")}}, can be used to instruct the browser to defer loading of images/iframes that are off-screen until the user scrolls near them. This allows non-critical resources to load only if needed, potentially speeding up initial page loads and reducing network usage. ```html <img loading="lazy" src="image.jpg" alt="..." /> <iframe loading="lazy" src="video-player.html" title="..."></iframe> ``` The `load` event fires when the eagerly-loaded content has all been loaded. At that time, it's entirely possible (or even likely) that there may be lazily-loaded images or iframes within the {{Glossary("visual viewport")}} that haven't yet loaded. You can determine if a given image has finished loading by examining the value of its Boolean {{domxref("HTMLImageElement.complete", "complete")}} property. #### Intersection Observer API [Intersection Observers](/en-US/docs/Web/API/IntersectionObserver) allow the user to know when an observed element enters or exits the browser's viewport. #### Event handlers When browser compatibility is crucial, there are a few options: - [polyfill intersection observer](https://github.com/w3c/IntersectionObserver) - fallback to scroll, resize or orientation change event handlers to determine if a specific element is in viewport ## Specifications {{Specifications}} ## See also - [Render blocking CSS](https://web.dev/articles/critical-rendering-path/render-blocking-css) - [Use lazy loading to improve loading speed](https://web.dev/articles/lazy-loading)
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/navigation_and_resource_timings/index.md
--- title: Navigation and resource timings slug: Web/Performance/Navigation_and_resource_timings page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} **Navigation timings** are metrics measuring a browser's document navigation events. **Resource timings** are detailed network timing measurements regarding the loading of an application's resources. Both provide the same read-only properties, but navigation timing measures the main document's timings whereas the resource timing provides the times for all the assets or resources called in by that main document and the resources' requested resources. The general performance timings below have been deprecated in favor of the Performance Entry API, which provides for marking and measuring times along the navigation and resource loading process. While deprecated, they are supported in all browsers. ## Performance Timings The [performanceTiming API](/en-US/docs/Web/API/PerformanceTiming), a JavaScript API for measuring the loading performance of the requested page, is deprecated but supported in all browsers. It has been replaced with the [performanceNavigationTiming](/en-US/docs/Web/API/PerformanceNavigationTiming) API. The performance timing API provided read only times, in milliseconds(ms), describing at what time each point in the page loading process was reached. As displayed in the image below, the navigation process goes from [`navigationStart`](/en-US/docs/Web/API/PerformanceTiming/navigationStart), [`unloadEventStart`](/en-US/docs/Web/API/PerformanceTiming/unloadEventStart), [`unloadEventEnd`](/en-US/docs/Web/API/PerformanceTiming/unloadEventEnd), [`redirectStart`](/en-US/docs/Web/API/PerformanceTiming/redirectStart), [`redirectEnd`](/en-US/docs/Web/API/PerformanceTiming/redirectEnd), [`fetchStart`](/en-US/docs/Web/API/PerformanceTiming/fetchStart), [`domainLookupStart`](/en-US/docs/Web/API/PerformanceTiming/domainLookupStart), [`domainLookupEnd`](/en-US/docs/Web/API/PerformanceTiming/domainLookupEnd), [`connectStart`](/en-US/docs/Web/API/PerformanceTiming/connectStart), [`connectEnd`](/en-US/docs/Web/API/PerformanceTiming/connectEnd), [`secureConnectionStart`](/en-US/docs/Web/API/PerformanceTiming/secureConnectionStart), [`requestStart`](/en-US/docs/Web/API/PerformanceTiming/requestStart), [`responseStart`](/en-US/docs/Web/API/PerformanceTiming/responseStart), [`responseEnd`](/en-US/docs/Web/API/PerformanceTiming/responseEnd), [`domLoading`](/en-US/docs/Web/API/PerformanceTiming/domLoading), [`domInteractive`](/en-US/docs/Web/API/PerformanceTiming/domInteractive), [`domContentLoadedEventStart`](/en-US/docs/Web/API/PerformanceTiming/domContentLoadedEventStart), [`domContentLoadedEventEnd`](/en-US/docs/Web/API/PerformanceTiming/domContentLoadedEventEnd), [`domComplete`](/en-US/docs/Web/API/PerformanceTiming/domComplete), [`loadEventStart`](/en-US/docs/Web/API/PerformanceTiming/loadEventStart), and [`loadEventEnd`](/en-US/docs/Web/API/PerformanceTiming/loadEventEnd). ![Navigation Timing event metrics](screen_shot_2019-05-03_at_1.06.27_pm.png) With the metrics above, and a bit of math, we can calculate many important metrics like [time to first byte](/en-US/docs/Glossary/Time_to_first_byte), page load time, dns lookup, and whether the connection is secure. To help measure the time it takes to complete all the steps, the Performance Timing API provides read only measurements of navigation timings. To view and capture our app's timing we enter: ```js let time = window.performance.timing; ``` We can then use the results to measure how well our app is performing. ![entering window.performance.timing in the console lists all the timings in the PerformanceNavigationTiming interface](navigatortiming.png) The order is: <table> <thead> <tr> <th>Performance Timings</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td> {{domxref("PerformanceTiming.navigationStart","navigationStart")}} </td> <td> When the prompt for unload terminates on the previous document in the same browsing context. If there is no previous document, this value will be the same as <code>PerformanceTiming.fetchStart</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.secureConnectionStart","secureConnectionStart")}} </td> <td> When the secure connection handshake starts. If no such connection is requested, it returns <code>0</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.redirectStart","redirectStart")}} </td> <td> When the first HTTP redirect starts. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is <code>0</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.redirectEnd","redirectEnd")}} </td> <td> <p> When the last HTTP redirect is completed, that is when the last byte of the HTTP response has been received. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is <code>0</code>. </p> </td> </tr> <tr> <td> {{domxref("PerformanceTiming.connectEnd","connectEnd")}} </td> <td> When the connection is opened network. If the transport layer reports an error and the connection establishment is started again, the last connection establishment end time is given. If a persistent connection is used, the value will be the same as <code>PerformanceTiming.fetchStart</code>. A connection is considered as opened when all secure connection handshake, or SOCKS authentication, is terminated. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.connectStart","connectStart")}} </td> <td> When the request to open a connection is sent to the network. If the transport layer reports an error and the connection establishment is started again, the last connection establishment start time is given. If a persistent connection is used, the value will be the same as <code>PerformanceTiming.fetchStart</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domainLookupEnd","domainLookupEnd")}} </td> <td> When the domain lookup is finished. If a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as <code>PerformanceTiming.fetchStart</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domainLookupStart","domainLookupStart")}} </td> <td> When the domain lookup starts. If a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as <code>PerformanceTiming.fetchStart</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.fetchStart","fetchStart")}} </td> <td> When the browser is ready to fetch the document using an HTTP request. This moment is <em>before</em> the check to any application cache. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.requestStart","requestStart")}} </td> <td> When the browser sent the request to obtain the actual document, from the server or from a cache. If the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.responseStart","responseStart")}} </td> <td> When the browser received the first byte of the response, from the server from a cache, or from a local resource. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.responseEnd","responseEnd")}} </td> <td> When the browser received the last byte of the response, or when the connection is closed if this happened first, from the server, the cache, or from a local resource. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domLoading","domLoading")}} </td> <td> When the parser started its work, that is when its {{domxref('Document.readyState')}} changes to <code>'loading'</code> and the corresponding {{DOMxRef("Document.readystatechange_event", "readystatechange")}} event is thrown. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.unloadEventStart","unloadEventStart")}} </td> <td> When the {{DOMxRef("Window.unload_event", "unload")}}> event has been thrown, indicating the time at which the previous document in the window began to unload. If there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value returned is <code>0</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.unloadEventEnd","unloadEventEnd")}} </td> <td> When the <code ><a href="/en-US/docs/Web/API/Window/unload_event">unload</a></code > event handler finishes. If there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is <code>0</code>. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domInteractive","domInteractive")}} </td> <td> When the parser finished its work on the main document, that is when its <a href="/en-US/docs/Web/API/Document/readyState" ><code>Document.readyState</code></a > changes to <code>'interactive'</code> and the corresponding <code ><a href="/en-US/docs/Web/API/Document/readystatechange_event" >readystatechange</a ></code > event is thrown. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domContentLoadedEventStart","domContentLoadedEventStart")}} </td> <td> Right before the parser sent the <code ><a href="/en-US/docs/Web/API/Document/DOMContentLoaded_event" >DOMContentLoaded</a ></code > event, that is right after all the scripts that need to be executed right after parsing have been executed. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domContentLoadedEventEnd","domContentLoadedEventEnd")}} </td> <td> Right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.domComplete","domComplete")}} </td> <td> When the parser finished its work on the main document, that is when its <a href="/en-US/docs/Web/API/Document/readyState" ><code>Document.readyState</code></a > changes to <code>'complete'</code> and the corresponding <code ><a href="/en-US/docs/Web/API/Document/readystatechange_event" >readystatechange</a ></code > event is thrown. </td> </tr> <tr> <td> {{domxref("PerformanceTiming.loadEventStart","loadEventStart")}} </td> <td> When the <code><a href="/en-US/docs/Web/API/Window/load_event">load</a></code> event was sent for the current document. If this event has not yet been sent, it returns <code>0.</code> </td> </tr> <tr> <td> {{domxref("PerformanceTiming.loadEventEnd","loadEventEnd")}} </td> <td> When the <code><a href="/en-US/docs/Web/API/Window/load_event">load</a></code> event handler terminated, that is when the load event is completed. If this event has not yet been sent, or is not yet completed, it returns <code>0.</code> </td> </tr> </tbody> </table> ### Calculating timings We can use these values to measure specific timings of interest: ```js const dns = time.domainLookupEnd - time.domainLookupStart; const tcp = time.connectEnd - time.connectStart; const tls = time.requestStart - time.secureConnectionStart; ``` ### Time to first byte [Time to First Byte](/en-US/docs/Glossary/Time_to_first_byte) is the time between the `navigationStart` (start of the navigation) and `responseStart`, (when the first byte of response data is received) available in the `performanceTiming` API: ```js const ttfb = time.responseStart - time.navigationStart; ``` ### Page load time [Page load time](/en-US/docs/Glossary/Page_load_time) is the time between `navigationStart` and the start of when the load event is sent for the current document. They are only available in the performanceTiming API. ```js let pageloadtime = time.loadEventStart - time.navigationStart; ``` ### DNS lookup time The DNS lookup time is the time between [`domainLookupStart`](/en-US/docs/Web/API/PerformanceResourceTiming/domainLookupStart) and [`domainLookupEnd`](/en-US/docs/Web/API/PerformanceResourceTiming/domainLookupEnd). These are both available in both the `performanceTiming` and `performanceNavigationTiming` APIs. ```js const dns = time.domainLookupEnd - time.domainLookupStart; ``` ### TCP The time it takes for the [TCP](/en-US/docs/Glossary/TCP) handshake is the time between the connection start and connection end: ```js const tcp = time.connectEnd - time.connectStart; ``` ### TLS negotiation [`secureConnectionStart`](/en-US/docs/Web/API/PerformanceResourceTiming/secureConnectionStart) will be `undefined` if not available, `0` if [HTTPS](/en-US/docs/Glossary/HTTPS) in not used, or a timestamp if available, and used. In other words, if a secure connection was used, `secureConnectionStart` will be [truthy](/en-US/docs/Glossary/Truthy), and the time between `secureConnectionStart` and `requestStart` will greater than 0. ```js const tls = time.requestStart - time.secureConnectionStart; ``` ## Performance Entry API The general performance timings above are deprecated but fully supported. We now have the {{domxref('PerformanceEntry', 'Performance Entry API')}}, which provides for marking and measuring times along the navigation and resource loading process. You can also create marks: ```js performance.getEntriesByType("navigation").forEach((navigation) => { console.dir(navigation); }); performance.getEntriesByType("resource").forEach((resource) => { console.dir(resource); }); performance.getEntriesByType("mark").forEach((mark) => { console.dir(mark); }); performance.getEntriesByType("measure").forEach((measure) => { console.dir(measure); }); performance.getEntriesByType("paint").forEach((paint) => { console.dir(paint); }); performance.getEntriesByType("frame").forEach((frame) => { console.dir(frame); }); ``` In supporting browsers, you can use `performance.getEntriesByType('paint')` to query the measure for `first-paint` and `first-contentful-paint`. We use `performance.getEntriesByType('navigation')` and `performance.getEntriesByType('resource')` to query the navigation and resource timings respectively. ## Navigation Timing When a user requests a website or application, [to populate the browser](/en-US/docs/Web/Performance/How_browsers_work) the user agent goes through a series of steps, including a {{glossary('DNS')}} lookup, {{glossary('TCP handshake')}}, and TLS negotiation, before the user agent makes the actual request and the servers return the requested assets. The browser then parses the content received, builds the DOM, CSSOM, accessibility, and render trees, eventually rendering the page. Once the user agent stops parsing the document, the user agent sets the document readiness to _interactive_. If there are deferred scripts needing to be parsed, it will do so, then fire the [DOMContentLoaded](/en-US/docs/Web/API/Document/DOMContentLoaded_event), after which the readiness is set to _complete_. The Document can now handle post-load tasks, after which point the document is marked as completely loaded. ```js const navigationTimings = performance.getEntriesByType("navigation"); ``` The `performance.getEntriesByType('navigation')` a returns an array of [PerformanceEntry](/en-US/docs/Web/API/PerformanceEntry) objects for the _navigation_ _type_. ![The results of when performance.getEntriesByType('navigation'); is entered into the console for this document](perfgentrybytypenavigation.png) A lot can be garnered from these timing. In the above image, we see via the _name_ property that the file being timed is this document For the rest of this explanation, we use the following variable: ```js const timing = performance.getEntriesByType("navigation")[0]; ``` ### Protocol We can check the protocol used by querying: ```js const protocol = timing.nextHopProtocol; ``` It returns the network protocol used to fetch the resource: in this case `h2` for `http/2`. ### Compression To get the compression savings percentage, we divide the transferSize by the decodedBodySize, and subtract that from 100%. We see a savings of over 74%. ```js const compressionSavings = 1 - timing.transferSize / timing.decodedBodySize; ``` We could have used ```js const compressionSavings = 1 - timing.encodedBodySize / timing.decodedBodySize; ``` but using `transferSize` includes the overhead bytes. For comparison, we can look at the network tab and see that we transferred 22.04KB for an uncompressed file size of 87.24KB. ![View of the bytes transferred and the size via the network tab](bytesdownloaded.png) If we do the math with these numbers, we get the same result: `1 - (22.04 / 87.24) = 0.747`. The navigation timings provide us a way to programmatically check transfer sizing and bandwidth savings. Note that this is the size for this single document alone: for this resource alone, not for all the resources combined. However, the duration, load events and DOM related timings have to do with the entire navigation, not this single asset. Client-side web applications may seem faster than this one with transfer sizes under 10000 and decoded body sizes under 30000, but that doesn't mean JavaScript, CSS, or media assets aren't adding bloat. Checking compression ratios is important but ensure to also check duration and the time between when the DOMContentLoaded event ended and when the DOM is complete, as running JavaScript on the main thread for long periods of time can lead to a non-responsive user interface. ### Request time The API doesn't provide every measurement you may desire. For example, how long did the request take? We can use measurements we do have, to get our answer. To measure the response time, subtract the request start time from the response start time. The request start is the moment immediately before the user agent starts requesting the resource from the server, or from relevant application caches or from local resources. The response start is the time immediately after the user agent's HTTP parser receives the first byte of the response from relevant application caches, or from local resources or from the server, which happens after the request is received and processed. ```js const request = timing.responseStart - timing.requestStart; ``` ### Load event duration By subtracting the timestamp from immediately before the load event of the current document is fired from the time when the load event of the current document is completed, you can measure the duration of the load event. ```js const load = timing.loadEventEnd - timing.loadEventStart; ``` ### DOMContentLoaded event The DOMContentLoaded event duration is measured by subtracting the time value immediately before the user agent fires the DOMContentLoaded event from the time value immediately after the event completes. Keeping this at 50ms or faster helps ensure a responsive user interface. ```js const DOMContentLoaded = timing.domContentLoadedEventEnd - timing.domContentLoadedEventStart; ``` ### Duration We are provided with the duration. The duration is the difference between the [PerformanceNavigationTiming.loadEventEnd](/en-US/docs/Web/API/PerformanceNavigationTiming/loadEventEnd) and [PerformanceEntry.startTime](/en-US/docs/Web/API/PerformanceEntry/startTime) properties. The PerformanceNavigationTiming interface also provides information about what type of navigation you are measuring, returning `navigate`, `reload`, `back_forward` or `prerender`. ## Resource timing Whereas navigation timing is for measuring the performance of the _main page_, generally the HTML file via which all the other assets are requested, resource timing measures timing for _individual resources_, the assets called in by the main page, and any assets that those resources request. Many of the measurements are similar: there is a DNS look up, TCP handshake and the secure connection start is done once per domain. ![Graphic of Resource Timing timestamps](resourcetiming-timestamps.jpg) The main thing to look at for each resource. ## See also - {{domxref("PerformanceNavigationTiming")}} - {{domxref("PerformanceResourceTiming")}}, - {{domxref("PerformanceMark")}} - {{domxref("PerformanceMeasure")}} - {{domxref("PerformancePaintTiming")}}
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/rum-vs-synthetic/index.md
--- title: "Performance Monitoring: RUM vs. synthetic monitoring" slug: Web/Performance/Rum-vs-Synthetic page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} **Synthetic monitoring** and **real user monitoring (RUM)** are two approaches for monitoring and providing insight into web performance. RUM and synthetic monitoring provide for different views of performance and have benefits, good use cases and shortfalls. RUM is generally best suited for understanding long-term trends whereas synthetic monitoring is very well suited to regression testing and mitigating shorter-term performance issues during development. In this article we define and compare these two performance monitoring approaches. ## Synthetic Monitoring Synthetic monitoring involves monitoring the performance of a page in a 'laboratory' environment, typically with automation tooling in a consistent as possible environment. Synthetic Monitoring involves deploying scripts to simulate the path an end user might take through a web application, reporting back the performance the simulator experiences. The traffic measured is not of your actual users, but rather synthetically generated traffic collecting data on page performance. An example of synthetic monitoring is [WebPageTest.org](https://WebPageTest.org). It is done in a controlled environment where variable like geography, network, device, browser, and cached status are predetermined. It provides waterfall charts for every asset served by the host and [CDN](/en-US/docs/Glossary/CDN) as well as every third party asset and asset requests generated by all third party scripts, such as ads and analytic services. Controlling for environmental variables is helpful in understanding where performance bottlenecks have been occurring and identifying the source of any performance issues. For example, but it isn't reflective of the actual experience of users, especially the long tail. Synthetic monitoring can be an important component of regression testing and production site monitoring. Test the site at every stage of development and regularly in production. Changes from baseline performance as part of continuous integration should fail a push. If an issue arises in production, synthetic monitoring can provide insight, helping identify, isolate, and resolve problems before they negatively user experience. ## Real User Monitoring **Real User Monitoring** or RUM measures the performance of a page from real users' machines. Generally, a third party script injects a script on each page to measure and report back on page load data for every request made. This technique monitors an application's actual user interactions. In real user monitoring, the browsers of real users report back performance metrics experienced. RUM helps identify how an application is being used, including the geographic distribution of users and the impact of that distribution on the end user experience. Unlike Synthetic monitoring, RUM captures the performance of actual users regardless of device, browser, network or geographic location. As users interact with an application, all performance timings are captured, regardless of what actions are taken or pages viewed. RUM monitors actual use cases, not the synthetic, assumed use cases predefined by an engineer, PM, or marketing team. This is particularly important for large sites or complex apps, where the functionality or content is constantly changing, and where the population accessing the application may differ greatly in life experiences from those creating it. By leveraging RUM, a business can better understand its users and identify the areas on its site that require the most attention. Moreover, RUM can help to understand the geographic or channel distribution trends of your users. Knowing your user trends helps you better define your business plan and, from a monitoring perspective, allows you to identify key areas to target for optimization and performance improvements. ## RUM v Synthetic Synthetic is well suited for catching regressions during development life cycles, especially with {{glossary('network throttling')}}. It is fairly easy, inexpensive, and great for spot-checking performance during development as an effective way to measure the effect of code changes, but it doesn't reflect what real users are experiencing and provides only a narrow view of performance. RUM, on the other hand, provides real metrics from real users using the site or application. While this is more expensive and likely less convenient, it provides vital user experience data. ## Performance APIs There are many monitoring services. If you do want to roll your own monitoring system, take a look at the performance APIs, mainly {{domxref("PerformanceNavigationTiming")}} and {{domxref("PerformanceResourceTiming")}}, but also {{domxref("PerformanceMark")}}, {{domxref("PerformanceMeasure")}}, and {{domxref("PerformancePaintTiming")}}.
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/critical_rendering_path/index.md
--- title: Critical rendering path slug: Web/Performance/Critical_rendering_path page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} The Critical Rendering Path is the sequence of steps the browser goes through to convert the HTML, CSS, and JavaScript into pixels on the screen. Optimizing the critical render path improves render performance. The critical rendering path includes the [Document Object Model](/en-US/docs/Web/API/Document_Object_Model) (DOM), [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model) (CSSOM), render tree and layout. The document object model is created as the HTML is parsed. The HTML may request JavaScript, which may, in turn, alter the DOM. The HTML includes or makes requests for styles, which in turn builds the CSS object model. The browser engine combines the two to create the Render Tree. Layout determines the size and location of everything on the page. Once layout is determined, pixels are painted to the screen. Optimizing the critical rendering path improves the time to first render. Understanding and optimizing the critical rendering path is important to ensure reflows and repaints can happen at 60 frames per second, to ensure performant user interactions, and to avoid [jank](/en-US/docs/Glossary/Jank). ## Understanding CRP Web performance includes the server requests and responses, loading, scripting, rendering, layout, and the painting of the pixels to the screen. A request for a web page or app starts with an HTTP request. The server sends a response containing the HTML. The browser then begins parsing the HTML, converting the received bytes to the DOM tree. The browser initiates requests every time it finds links to external resources, be it stylesheets, scripts, or embedded image references. Some requests are blocking, which means the parsing of the rest of the HTML is halted until the imported asset is handled. The browser continues to parse the HTML making requests and building the DOM, until it gets to the end, at which point it constructs the CSS object model. With the DOM and CSSOM complete, the browser builds the render tree, computing the styles for all the visible content. After the render tree is complete, layout occurs, defining the location and size of all the render tree elements. Once complete, the page is rendered, or 'painted' on the screen. ### Document Object Model DOM construction is incremental. The HTML response turns into tokens which turns into nodes which turn into the DOM Tree. A single DOM node starts with a startTag token and ends with an endTag token. Nodes contain all relevant information about the HTML element. The information is described using tokens. Nodes are connected into a DOM tree based on token hierarchy. If another set of startTag and endTag tokens come between a set of startTag and endTags, you have a node inside a node, which is how we define the hierarchy of the DOM tree. The greater the number of nodes, the longer the following events in the critical rendering path will take. Measure! A few extra nodes won't make a big difference, but keep in mind that adding many extra nodes will impact performance. ### CSS Object Model The DOM contains all the content of the page. The CSSOM contains all the information on how to style the DOM. CSSOM is similar to the DOM, but different. While the DOM construction is incremental, CSSOM is not. CSS is render blocking: the browser blocks page rendering until it receives and processes all the CSS. CSS is render blocking because rules can be overwritten, so the content can't be rendered until the CSSOM is complete. CSS has its own set of rules for identifying valid tokens. Remember the C in CSS stands for 'Cascade'. CSS rules cascade down. As the parser converts tokens to nodes, descendant nodes will inherit some of the styles of the parent. The incremental processing features don't apply to CSS like they do with HTML, because subsequent rules may override previous ones. The CSS object model gets built as the CSS is parsed, but can't be used to build the render tree until it is completely parsed because styles that are going to be overwritten with later parsing should not be rendered to the screen. In terms of selector performance, less specific selectors are faster than more specific ones. For example, `.foo {}` is faster than `.bar .foo {}` because when the browser finds `.foo`, in the second scenario, it has to walk up the DOM to check if `.foo` has an ancestor `.bar`. The more specific tag requires more work from the browser, but this penalty is not likely worth optimizing around. If you measure the time it takes to parse CSS, you'll be amazed at how fast browsers truly are. The more specific rule is more expensive because it has to traverse more nodes in the DOM tree - but that extra expense is generally minimal. Measure first. Optimize as needed. Specificity is likely not your lowest hanging fruit. When it comes to CSS, selector performance optimization improvements will only be in microseconds. There are other [ways to optimize CSS](/en-US/docs/Learn/Performance/CSS), such as minification, and separating deferred CSS into non-blocking requests by using media queries. ### Render Tree The render tree captures both the content and the styles: the DOM and CSSOM trees are combined into the render tree. To construct the render tree, the browser checks every node, starting from root of the DOM tree, and determines which CSS rules are attached. The render tree only captures visible content. The head section (generally) doesn't contain any visible information, and is therefore not included in the render tree. If there's a `display: none;` set on an element, neither it, nor any of its descendants, are in the render tree. ### Layout Once the render tree is built, layout becomes possible. Layout is dependent on the size of screen. The layout step determines where and how the elements are positioned on the page, determining the width and height of each element, and where they are in relation to each other. What is the width of an element? Block level elements, by definition, have a default width of 100% of the width of their parent. An element with a width of 50%, will be half of the width of its parent. Unless otherwise defined, the body has a width of 100%, meaning it will be 100% of the width of the viewport. This width of the device impacts layout. The viewport meta tag defines the width of the layout viewport, impacting the layout. Without it, the browser uses the default viewport width, which on by-default full screen browsers is generally 960px. On by-default full screen browsers, like your phone's browser, by setting `<meta name="viewport" content="width=device-width">`, the width will be the width of the device instead of the default viewport width. The device-width changes when a user rotates their phone between landscape and portrait mode. Layout happens every time a device is rotated or browser is otherwise resized. Layout performance is impacted by the DOM — the greater the number of nodes, the longer layout takes. Layout can become a bottleneck, leading to jank if required during scrolling or other animations. While a 20ms delay on load or orientation change may be fine, it will lead to jank on animation or scroll. Any time the render tree is modified, such as by added nodes, altered content, or updated box model styles on a node, layout occurs. To reduce the frequency and duration of layout events, batch updates and avoid animating box model properties. ### Paint The last step is painting the pixels to the screen. Once the render tree is created and layout occurs, the pixels can be painted to the screen. On load, the entire screen is painted. After that, only impacted areas of the screen will be repainted, as browsers are optimized to repaint the minimum area required. Paint time depends on what kind of updates are being applied to the render tree. While painting is a very fast process, and therefore likely not the most impactful place to focus on in improving performance, it is important to remember to allow for both layout and re-paint times when measuring how long an animation frame may take. The styles applied to each node increase the paint time, but removing style that increases the paint by 0.001ms may not give you the biggest bang for your optimization buck. Remember to measure first. Then you can determine whether it should be an optimization priority. ## Optimizing for CRP Improve page load speed by prioritizing which resources get loaded, controlling the order in which they are loaded, and reducing the file sizes of those resources. Performance tips include 1) minimizing the number of critical resources by deferring non-critical ones' download, marking them as async, or eliminating them altogether, 2) optimizing the number of requests required along with the file size of each request, and 3) optimizing the order in which critical resources are loaded by prioritizing the downloading of critical assets, thereby shortening the critical path length.
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/optimizing_startup_performance/index.md
--- title: Optimizing startup performance slug: Web/Performance/Optimizing_startup_performance page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} Improving your startup performance is often one of the highest value performance optimizations that can be made. How long does your app take to start up? Does it seem to lock up the device or the user's browser while the app loads? That makes users worry that your application has crashed, or that something else is wrong. Good user experience includes ensuring your app loads quickly. This article provides performance tips and suggestions for both writing new applications and porting applications to the web from other platforms. ## Fast asynchronous loading Regardless of platform, it's always a good idea to start up as **quickly** as possible. Since that's a universal issue, we won't be focusing on it too much here. Instead, we're going to look at a more important issue when building Web apps: starting up as **asynchronously** as possible. That means not running all your startup code in a single event handler on the app's main thread. Rather, create a [Web worker](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) that does as much as possible in a background thread (for example, fetching and processing data.) Relegating tasks to a Web worker frees up the main thread for tasks requiring it, like user events and rendering UI. In turn, main thread events should consist of many small tasks, also known as [micro tasks](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth), rather than larger, more time consuming tasks. Asynchronous loading helps prevent pages and user interfaces from appearing to be (or actually becoming) unresponsive. By minimizing the time required for any individual loading task, the application's [event loop](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth#event_loops) will continue to cycle while it starts up. This will prevent the application, browser, and/or device from appearing frozen. In the worst case, blocking the main thread can cause users to uninstall your app; for example, if someone launches your app by mistake and they aren't prevented from closing the application, they may want to take action so that doesn't accidentally happen again. ## Where there's a will… It is easier to just write everything the "right way" the first time then it is to retrofit for performance (and accessibility). When you are starting from scratch, making appropriate bits of code asynchronous means a retrofit isn't necessary. All pure startup calculations should be performed in background threads, while you keep the run-time of main thread events as short as possible. Instead of including a progress indicator so the user knows what's going on and how long they'll be waiting, make the progress bar unnecessary. On the other hand, porting an existing app to the Web can be challenging. Native application don't need to be written in an asynchronous fashion because the operating system usually handles loading for you. The source application might have a main loop that can easily be made to operate asynchronously (by running each main loop iteration separately); startup is often just a continuous, monolithic procedure that might periodically update a progress meter. While you can use [Web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) to run even very large, long-duration chunks of [JavaScript](/en-US/docs/Web/JavaScript) code asynchronously, there's a huge caveat: Web workers can't directly manipulate the [DOM](/en-US/docs/Web/API/Document_Object_Model) and have limited access to methods and properties of the [window](/en-US/docs/Web/API/Window) object, including no access to [WebGL](/en-US/docs/Web/API/WebGL_API). This all means that unless you can easily pull out the "pure calculation" chunks of your startup process into workers, you'll wind up having to run most or all of your startup code on the main thread. However, even code like that can be made asynchronous, with a little work. ## Getting asynchronous Here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a new app or a port): - Use the [`defer`](/en-US/docs/Web/HTML/Element/script#defer) or [`async`](/en-US/docs/Web/HTML/Element/script#async) attribute on script tags needed by the Web application. This allows HTML parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. - If you need to decode asset files (for example, decoding JPEG files and turning them into raw texture data for later use by WebGL), that's great to do in workers. - When dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase. The provided one is almost certainly significantly faster, and will reduce your app size to boot. In addition, the browser may automatically parallelize these decoders. - Any data processing that can be done in parallel should be. Don't do one chunk of data after another; do them all at once when possible! - Don't include scripts or stylesheets that don't participate in the [critical rendering path](/en-US/docs/Web/Performance/Critical_rendering_path) in your startup HTML file. Load them only when needed. - Reduce the size of your JavaScript files. Try to send the minified version of the file to the browser and use compression like Gzip or Brotli. - Utilize resource hints (like preconnect or preload) whenever possible to indicate to the browser which files are more critical for your application. The more stuff you can do asynchronously, the better advantage your app can take of multicore processors. ### Porting issues Once the initial loading is done and the app's main code starts to run, it's possible your app has to be single-threaded, especially if it's a port. The most important thing to do to try to help with the main code's startup process is to refactor the code into small pieces. These can then be executed in chunks interspersed across multiple calls to your app's main loop (so that the main thread gets to handle input and the like). Emscripten provides an API to help with this refactoring; for example, you can use `emscripten_push_main_loop_blocker()` to establish a function to be executed before the main thread is allowed to continue. By establishing a queue of functions to be called in sequence, you can more easily manage running bits of code without blocking the main thread. That leaves, though, the problem of having to refactor your existing code to actually work that way. That can take some time. ### How asynchronous should I get? The faster your site first becomes usable and the more responsive it is to user input, the better it will be perceived. A site that takes 1 or 2 seconds before content first appears is usually seen as fast; if you're used to sites taking 3 or 4 seconds, then 7 or 8 seconds feels like a very long time. In terms of responsiveness, users won't notice a delay of 50ms or less. Any delay of over 200ms and the user will perceive your site as sluggish. When working to improve the loading and responsiveness of your applications, remember that many of your users may have older, slower computer than yours, they may experience longer delays than you do! ## Other suggestions There are other things beyond going asynchronous, which can help you improve your app's startup time. Here are a few of them: - Download time - : Keep in mind how long it will take the user to download your application's data. If your application is very popular, or has to re-download content frequently, you should try to have as fast a hosting server as possible. Always [compress](/en-US/docs/Glossary/GZip_compression) your data to make it as small as you can. - Data size - : Do your best to optimize the size of your data; smaller level files will download and be processed faster than larger ones. - Subjective factors - : Anything you can do to help keep the user engaged during the startup process will help make the time seem to go by faster. Displaying a mock splash screen can improve [perceived performance](/en-US/docs/Learn/Performance/Perceived_performance). For heavy sites, anything you can do to help the user feel like your app is doing something instead of sitting there quietly helps. ## See also - [Apps](/en-US/docs/Web/Progressive_web_apps) - [Games](/en-US/docs/Games) - [BananaBread (or any compiled codebase) Startup Experience](https://mozakai.blogspot.com/2012/07/bananabread-or-any-compiled-codebase.html) (2012)
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/dns-prefetch/index.md
--- title: Using dns-prefetch slug: Web/Performance/dns-prefetch page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} **`DNS-prefetch`** is an attempt to resolve domain names before resources get requested. This could be a file loaded later or link target a user tries to follow. ## Why use dns-prefetch? When a browser requests a resource from a (third party) server, that [cross-origin](/en-US/docs/Web/HTTP/CORS)'s domain name must be resolved to an IP address before the browser can issue the request. This process is known as DNS resolution. While DNS caching can help to reduce this latency, DNS resolution can add significant latency to requests. For websites that open connections to many third parties, this latency can significantly reduce loading performance. `dns-prefetch` helps developers mask DNS resolution latency. The [HTML `<link>` element](/en-US/docs/Web/HTML/Element/link) offers this functionality by way of a [`rel` attribute](/en-US/docs/Web/HTML/Attributes/rel) value of `dns-prefetch`. The [cross-origin](/en-US/docs/Web/HTTP/CORS) domain is then specified in the [href attribute](/en-US/docs/Web/HTML/Attributes): ## Syntax ```html <link rel="dns-prefetch" href="https://fonts.googleapis.com/" /> ``` ## Examples ```html <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <link rel="dns-prefetch" href="https://fonts.googleapis.com/" /> <!-- and all other head elements --> </head> <body> <!-- your page content --> </body> </html> ``` You should place `dns-prefetch` hints in the [`<head>` element](/en-US/docs/Web/HTML/Element/head) any time your site references resources on cross-origin domains, but there are some things to keep in mind. ## Best practices There are 3 main things to keep in mind: **For one**, `dns-prefetch` is only effective for DNS lookups on [cross-origin](/en-US/docs/Web/HTTP/CORS) domains, so avoid using it to point to your site or domain. This is because the IP behind your site's domain will have already been resolved by the time the browser sees the hint. **Second**, it's also possible to specify `dns-prefetch` (and other resources hints) as an [HTTP header](/en-US/docs/Web/HTTP/Headers) by using the [HTTP Link field](/en-US/docs/Web/HTTP/Headers/Link): ```http Link: <https://fonts.googleapis.com/>; rel=dns-prefetch ``` **Third**, while `dns-prefetch` only performs a DNS lookup, `preconnect` establishes a connection to a server. This process includes DNS resolution, as well as establishing the TCP connection, and performing the [TLS](/en-US/docs/Glossary/TLS) handshake—if a site is served over HTTPS. Using `preconnect` provides an opportunity to further reduce the perceived latency of [cross-origin requests](/en-US/docs/Web/HTTP/CORS). You can use it as an [HTTP header](/en-US/docs/Web/HTTP/Headers) by using the [HTTP Link field](/en-US/docs/Web/HTTP/Headers/Link): ```http Link: <https://fonts.googleapis.com/>; rel=preconnect ``` or via the [HTML `<link>` element](/en-US/docs/Web/HTML/Element/link): ```html <link rel="preconnect" href="https://fonts.googleapis.com/" crossorigin /> ``` > **Note:** If a page needs to make connections to many third-party domains, preconnecting them all is counterproductive. The `preconnect` hint is best used for only the most critical connections. For the others, just use `<link rel="dns-prefetch">` to save time on the first step — the DNS lookup. The logic behind pairing these hints is because support for dns-prefetch is better than support for preconnect. Browsers that don't support preconnect will still get some added benefit by falling back to dns-prefetch. Because this is an HTML feature, it is very fault-tolerant. If a non-supporting browser encounters a dns-prefetch hint—or any other resource hint—your site won't break. You just won't receive the benefits it provides. Some resources such as fonts are loaded in anonymous mode. In such cases you should set the [crossorigin](/en-US/docs/Web/HTML/Attributes/crossorigin) attribute with the preconnect hint. If you omit it, the browser will only perform the DNS lookup. ## See also - [\<link>](/en-US/docs/Web/HTML/Element/link) - [HTML attribute: rel](/en-US/docs/Web/HTML/Attributes/rel) - [crossorigin](/en-US/docs/Web/HTML/Attributes/crossorigin) - [Cross-Origin Resource Sharing (CORS)](/en-US/docs/Web/HTTP/CORS) - [HTTP headers](/en-US/docs/Web/HTTP/Headers) - [HTTP header Link](/en-US/docs/Web/HTTP/Headers/Link)
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/css_javascript_animation_performance/index.md
--- title: CSS and JavaScript animation performance slug: Web/Performance/CSS_JavaScript_animation_performance page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} Animations are critical for a pleasurable user experience on many applications. There are many ways to implement web animations, such as CSS {{cssxref("transition","transitions")}}/{{cssxref("animation","animations")}} or JavaScript-based animations (using {{domxref("Window.requestAnimationFrame","requestAnimationFrame()")}}). In this article, we analyze the performance differences between CSS-based and JavaScript-based animation. ## CSS transitions and animations Both CSS transitions and animations can be used to write animation. They each have their own user scenarios: - CSS {{cssxref("transition","transitions")}} provide an easy way to make animations occur between the current style and an end CSS state, e.g., a resting button state and a hover state. Even if an element is in the middle of a transition, the new transition starts from the current style immediately instead of jumping to the end CSS state. See [Using CSS transitions](/en-US/docs/Web/CSS/CSS_transitions/Using_CSS_transitions) for more details. - CSS {{cssxref("animation","animations")}}, on the other hand, allow developers to make animations between a set of starting property values and a final set rather than between two states. CSS animations consist of two components: a style describing the CSS animation, and a set of key frames that indicate the start and end states of the animation's style, as well as possible intermediate points. See [Using CSS animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations) for more details. In terms of performance, there is no difference between implementing an animation with CSS transitions or animations. Both of them are classified under the same CSS-based umbrella in this article. ## requestAnimationFrame The {{domxref("Window.requestAnimationFrame","requestAnimationFrame()")}} API provides an efficient way to make animations in JavaScript. The callback function of the method is called by the browser before the next repaint on each frame. Compared to {{domxref("setTimeout()")}}/{{domxref("setInterval()")}}, which need a specific delay parameter, `requestAnimationFrame()` is much more efficient. Developers can create an animation by changing an element's style each time the loop is called (or updating the Canvas draw, or whatever.) > **Note:** Like CSS transitions and animations, `requestAnimationFrame()` pauses when the current tab is pushed into the background. For more details read [animating with JavaScript from setInterval to requestAnimationFrame](https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/). ## Performance comparison:<br>transitions vs. requestAnimationFrame The fact is that, in most cases, the performance of CSS-based animations is almost the same as JavaScripted animations — in Firefox at least. Some JavaScript-based animation libraries, like [GSAP](https://greensock.com/gsap/) and [Velocity.JS](http://velocityjs.org/), even claim that they are able to achieve better performance than [native CSS transitions/animations](https://css-tricks.com/myth-busting-css-animations-vs-javascript/). This can occur because CSS transitions/animations are resampling element styles in the main UI thread before each repaint event happens, which is almost the same as resampling element styles via a `requestAnimationFrame()` callback, also triggered before the next repaint. If both animations are made in the main UI thread, there is no difference performance-wise. In this section we'll walk you through a performance test, using Firefox, to see what animation method seems better overall. ### Enabling FPS tools Before going through the example, please enable FPS tools first to see the current frame rate: 1. In the URL bar, enter _about:config_; click the `I'll be careful, I promise!` button to enter the config screen. ![Warning screen that changing settings can be risky, with a button to accept risks.](pic1.png) 2. In the search bar, search for the `layers.acceleration.draw-fps` preference. 3. Double-click the entry to set the value to `true`. Now you will be able to see three little purple boxes in the upper left corner of the Firefox window. The first box represents FPS. ![Entering the search term filters the options. Only the layers.acceleration.draw-fps preference is showing and is set to true. Three numbers (001, 001, and 108) are appearing in the upper left corner of the browser, overlaying its UI.](pic2.png) ### Running the performance test Initially in the test seen below, a total of 1000 {{htmlelement("div")}} elements are transformed by CSS animation. ```js const boxes = []; const button = document.getElementById("toggle-button"); const boxContainer = document.getElementById("box-container"); const animationType = document.getElementById("type"); // create boxes for (let i = 0; i < 1000; i++) { const div = document.createElement("div"); div.classList.add("css-animation"); div.classList.add("box"); boxContainer.appendChild(div); boxes.push(div.style); } let toggleStatus = true; let rafId; button.addEventListener("click", () => { if (toggleStatus) { animationType.textContent = " requestAnimationFrame"; for (const child of boxContainer.children) { child.classList.remove("css-animation"); } rafId = window.requestAnimationFrame(animate); } else { window.cancelAnimationFrame(rafId); animationType.textContent = " CSS animation"; for (const child of boxContainer.children) { child.classList.add("css-animation"); } } toggleStatus = !toggleStatus; }); const duration = 6000; const translateX = 500; const rotate = 360; const scale = 1.4 - 0.6; let start; function animate(time) { if (!start) { start = time; rafId = window.requestAnimationFrame(animate); return; } const progress = (time - start) / duration; if (progress < 2) { let x = progress * translateX; let transform; if (progress >= 1) { x = (2 - progress) * translateX; transform = `translateX(${x}px) rotate(${ (2 - progress) * rotate }deg) scale(${0.6 + (2 - progress) * scale})`; } else { transform = `translateX(${x}px) rotate(${progress * rotate}deg) scale(${ 0.6 + progress * scale })`; } for (const box of boxes) { box.transform = transform; } } else { start = null; } rafId = window.requestAnimationFrame(animate); } ``` ```html hidden <div id="header"> <button id="toggle-button">Toggle</button> <span id="type">CSS Animation</span> </div> <div id="box-container"></div> ``` ```css hidden #header { position: sticky; top: 0.5rem; margin: 0 0.5rem; z-index: 100; background-color: lightgreen; } #box-container { margin-top: 1.5rem; display: grid; grid-template-columns: repeat(40, 1fr); gap: 15px; } .box { width: 30px; height: 30px; background-color: red; } .css-animation { animation: animate 6s linear 0s infinite alternate; } @keyframes animate { 0% { transform: translateX(0) rotate(0deg) scale(0.6); } 100% { transform: translateX(500px) rotate(360deg) scale(1.4); } } ``` {{ EmbedLiveSample("Running the performance test", "100%", "480") }} The animation can be switched to `requestAnimationFrame()` by clicking the toggle button. Try running them both now, comparing the FPS for each (the first purple box.) You should see that the performance of CSS animations and `requestAnimationFrame()` are very close. ### Off main thread animation Even given the test results above, we'd argue that CSS animations are the better choice. But how? The key is that as long as the properties we want to animate do not trigger reflow/repaint (read [CSS triggers](https://csstriggers.com/) for more information), we can move those sampling operations out of the main thread. The most common property is the CSS transform. If an element is promoted as a [layer](https://wiki.mozilla.org/Gecko:Overview#Graphics), animating transform properties can be done in the GPU, meaning better performance/efficiency, especially on mobile. Find out more details in [OffMainThreadCompositing](https://wiki.mozilla.org/Platform/GFX/OffMainThreadCompositing). To enable the OMTA (Off Main Thread Animation) in Firefox, you can go to _about:config_ and search for the `layers.offmainthreadcomposition.async-animations`. Toggle its value to `true`. ![Entering the search term filters the options. Only the layers.offmainthreadcomposition.async-animations preference is showing, set to true. The three numbers in the upper left corner of the browser, above its UI, have increased to 005, 003, and 108.](pic3.png) After enabling OMTA, try running the above test again. You should see that the FPS of the CSS animations will now be significantly higher. > **Note:** In Nightly/Developer Edition, you should see that OMTA is enabled by default, so you might have to do the tests the other way around (test with it enabled first, then disable to test without OMTA.) ## Summary Browsers are able to optimize rendering flows. In summary, we should always try to create our animations using CSS transitions/animations where possible. If your animations are really complex, you may have to rely on JavaScript-based animations instead.
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/performance_budgets/index.md
--- title: Performance budgets slug: Web/Performance/Performance_budgets page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} A performance budget is a limit to prevent regressions. It can apply to a file, a file type, all files loaded on a page, a specific metric (e.g. [Time to Interactive](/en-US/docs/Glossary/Time_to_interactive)), a custom metric (e.g. Time to Hero Element), or a threshold over a period of time. ## Why do I need a performance budget? A budget exists to reflect your reachable goals. It's a tradeoff between user experience, against other performance indicators (e.g. conversion rate). These goals can be: - Timing based (e.g. [Time to Interactive](/en-US/docs/Glossary/Time_to_interactive), [First Contentful Paint](/en-US/docs/Glossary/First_contentful_paint)). - Quantity-based (e.g. amount of JS files/total image size). - Rule-based (e.g. PageSpeed index, Lighthouse score). Their primary goal is to prevent regressions, but they can provide insights to forecast trends (i.e. On September, 50% of the budget was spent in a week). Additionally, it can uncover development needs (i.e. A large library with smaller alternatives is often picked to solve a common problem). ## How do I define a performance budget? A budget should include 2 levels: - Warning. - Error. The warning level allows you to be proactive and plan any tech debt, while not blocking development or deploys. The error level is an upper bound limit, where changes will have a negative and noticeable impact. In order to begin, you need to first measure the devices and connection speeds where your users are coming from (e.g. A \~$_200_ Android device over a 3G connection), using multiple [tools](/en-US/docs/Learn/Performance/Web_Performance_Basics). These time-based metrics will translate into file-size budgets. A default baseline to reduce bounce rate is to achieve [Time to Interactive under 5 seconds in 3G/4G, and under 2 seconds for subsequent loads](https://infrequently.org/2017/10/can-you-afford-it-real-world-web-performance-budgets/). However, based on the specific goals and content of your site, you might choose to focus on other metrics. For a text-heavy site such as a blog or a news site, the [First Contentful Paint](/en-US/docs/Glossary/First_contentful_paint) metric could reflect more closely the user behavior. (i.e. How fast can users start reading), which will inform file specific budgets (e.g. Font size), and their optimizations. (e.g. Using [font-display](/en-US/docs/Web/CSS/@font-face/font-display) to improve [Perceived Performance](/en-US/docs/Learn/Performance/Perceived_performance)). The ultimate value of a Performance Budget is to correlate the impact of Performance on business or product goals. When defining metrics, you should focus on [User Experience](https://extensionworkshop.com/documentation/develop/user-experience-best-practices/), which will dictate not only the bounce or conversion rate but how likely is that user to return. ## How do I implement a performance budget? During development, there are a few tools to run checks against new or modified assets: - A module bundler (e.g. [webpack](https://webpack.js.org/)), has [performance features](https://webpack.js.org/configuration/performance/) that will notify you when assets exceed specified limits. - [Bundlesize](https://github.com/siddharthkp/bundlesize), allows you to define and run file size checks in your continuous integration (CI) pipeline. File size checks are the first line of defense against regressions but translating size back into time metrics can be difficult since development environments could be missing 3rd party scripts, and optimizations commonly provided by a [CDN](/en-US/docs/Glossary/CDN). The first step is to define a development baseline for each branch to compare to and the precision of the difference between development and production can be used as a goal towards better match the live environment. The [Lighthouse Bot](https://github.com/GoogleChromeLabs/lighthousebot) integrates with [Travis CI](https://travis-ci.org/) and can be used to gather [Lighthouse](https://developer.chrome.com/docs/lighthouse/overview/) and [Webpage Test](https://webpagetest.org) metrics from a development URL. The bot will pass or fail based on the provided minimum scores. ## How do I enforce a performance budget? The sooner that you can identify a potential addition pushing the budget, the better you can analyze the current state of your site, and pinpoint optimizations or unnecessary code. However, you should have multiple budgets and be dynamic. They are meant to reflect your ongoing goals but allow risks and experiments. For example, you may introduce a feature that increases overall load time but attempts to increase user engagement. (i.e. How long a user stays on a page or site). A performance budget helps you protect optimal behavior for your current users while enabling you to tap into new markets and deliver custom experiences. ## See also - [Start Performance Budgeting](https://addyosmani.com/blog/performance-budgets/) by Addy Osmani - [Performance Budgets 101](https://web.dev/articles/performance-budgets-101) by Milica Mihajlija - [Performance Budgets That Stick](https://timkadlec.com/remembers/2019-03-07-performance-budgets-that-stick/) by Tim Kadlec
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/understanding_latency/index.md
--- title: Understanding latency slug: Web/Performance/Understanding_latency page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} **Latency** is the time it takes for a packet of data to travel from source to a destination. In terms of performance optimization, it's important to optimize to reduce causes of latency and to test site performance emulating high latency to optimize for users with lousy connections. This article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it. ## What is Latency? Latency is generally considered to be the amount of time it takes from when a request is made by the user to the time it takes for the response to get back to that user. On a first request, for the first 14Kb bytes, latency is longer because it includes a {{glossary('DNS')}} lookup, a {{glossary('TCP handshake')}}, the secure {{glossary('TLS')}} negotiation. Subsequent requests will have less latency because the connection to the server is already set. Latency describes the amount of delay on a network or Internet connection. Low latency implies that there are no or almost no delays. High latency implies that there are many delays. One of the main aims of improving performance is to reduce latency. The latency associated with a single asset, especially a basic HTML page, may seem trivial. But websites generally involve multiple requests: the HTML includes requests for multiple CSS, scripts, and media files. The greater the number and size of these requests, the greater the impact of high latency on user experience. On a connection with low latency, requested resources will appear almost immediately. On a connection with high latency, there will be a discernible delay between the time that a request is sent, and the resources are returned. We can determine the amount of latency by measuring the speed with which the data moves from one network location to another. Latency can be measured one way, for example, the amount of time it takes to send a request for resources, or the length of the entire round-trip from the browser's request for a resource to the moment when the requested resource arrives at the browser. ## Network throttling To emulate the latency of a low bandwidth network, you can use developer tools and switch to a lower end network connection. ![Emulate latency by emulating throttling](emulate_latency.png) In the developer tools, under the network table, you can switch the throttling option to 2G, 3G, etc. Different browser developer tools have different preset options, the characteristics emulated include download speed, upload speed, and minimum latency, or the minimum amount of time it takes to send a packet of data. The approximate values of some presets include: | Selection | Download speed | Upload speed | Minimum latency (ms) | | -------------- | -------------- | ------------ | -------------------- | | GPRS | 50 Kbps | 20 Kbps | 500 | | Regular 2G | 250 Kbps | 50 Kbps | 300 | | Good 2G | 450 Kbps | 150 Kbps | 150 | | Regular 3G | 750 Kbps | 250 Kbps | 100 | | Good 3G | 1.5 Mbps | 750 Kbps | 40 | | Regular 4G/LTE | 4 Mbps | 3 Mbps | 20 | | DSL | 2 Mbps | 1 Mbps | 5 | | Wi-Fi | 30 Mbps | 15 Mbps | 2 | ## Network Timings Also, on the network tab, you can see how long each request took to complete. We can look at how long a 267.5Kb SVG image asset took to download. ![The time it took for a large SVG asset to load.](latencymlw.png) When a request is in a queue, waiting for a network connection it is considered **blocked**. Blocking happens when there are too many simultaneous connections made to a single server over HTTP. If all connections are in use, the browser can't download more resources until a connection is released, meaning those requests and resources are blocked. **DNS resolution** is the time it took to do the {{glossary('DNS')}} lookup. The greater the number of [hostnames](/en-US/docs/Web/API/URL/hostname), the more DNS lookups need to be done. **Connecting** is the time it takes for a {{glossary('TCP handshake')}} to complete. Like DNS, the greater the number of server connections needed, the more time is spent creating server connections. The **{{glossary('TLS')}} handshake** is how long it took to set up a secure connection. While a TLS handshake does take longer to connect than an insecure connection, the additional time needed for a secure connection is worth it. **Sending** is the time taken to send the HTTP request to the server. **Waiting** is disk latency, the time it took for the server to complete its response. Disk latency used to be the main area of performance concern. However, server performance has improved as computer memory, or CPU, has improved. Depending on the complexity of what is needed from the server, this can still be an issue. **Receiving** is the time it takes to download the asset. The receiving time is determined by a combination of the network capacity and the asset file size. If the image been cached, this would have been nearly instantaneous. Had we throttled, receiving could have been 43 seconds! ## Measuring latency **Network latency** is the time it takes for a data request to get from the computer making the request, to the computer responding. Including the time it takes for a byte of data to make it from the responding computer back to the requesting computer. It is generally measured as a round trip delay. **Disk latency** is the time it takes from the moment a computer, usually a server, receives a request, to the time the computer returns the response.
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/how_browsers_work/index.md
--- title: "Populating the page: how browsers work" slug: Web/Performance/How_browsers_work page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} Users want web experiences with content that is fast to load and smooth to interact with. Therefore, a developer should strive to achieve these two goals. To understand how to improve performance and perceived performance, it helps to understand how the browser works. ## Overview Fast sites provide better user experiences. Users want and expect web experiences with content that is fast to load and smooth to interact with. Two major issues in web performance are issues having to do with latency and issues having to do with the fact that for the most part, browsers are single-threaded. Latency is the biggest threat to our ability to ensure a fast-loading page. It is the developers' goal to make the site load as fast as possible — or at least _appear_ to load super fast — so the user gets the requested information as quickly as possible. Network latency is the time it takes to transmit bytes over the air to computers. Web performance is what we have to do to make the page load as quickly as possible. For the most part, browsers are considered single-threaded. That is, they execute a task from beginning to end before taking up another task. For smooth interactions, the developer's goal is to ensure performant site interactions, from smooth scrolling to being responsive to touch. Render time is key, ensuring the main thread can complete all the work we throw at it and still always be available to handle user interactions. Web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate. ## Navigation _Navigation_ is the first step in loading a web page. It occurs whenever a user requests a page by entering a URL into the address bar, clicking a link, submitting a form, as well as other actions. One of the goals of web performance is to minimize the amount of time navigation takes to complete. In ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes that can cause delays. ### DNS lookup The first step of navigating to a web page is finding where the assets for that page are located. If you navigate to `https://example.com`, the HTML page is located on the server with IP address of `93.184.216.34`. If you've never visited this site, a DNS lookup must happen. Your browser requests a DNS lookup, which is eventually fielded by a name server, which in turn responds with an IP address. After this initial request, the IP will likely be cached for a time, which speeds up subsequent requests by retrieving the IP address from the cache instead of contacting a name server again. DNS lookups usually only need to be done once per hostname for a page load. However, DNS lookups must be done for each unique hostname the requested page references. If your fonts, images, scripts, ads, and metrics all have different hostnames, a DNS lookup will have to be made for each one. ![Mobile requests go first to the cell tower, then to a central phone company computer before being sent to the internet](latency.jpg) This can be problematic for performance, particularly on mobile networks. When a user is on a mobile network, each DNS lookup has to go from the phone to the cell tower to reach an authoritative DNS server. The distance between a phone, a cell tower, and the name server can add significant latency. ### TCP handshake Once the IP address is known, the browser sets up a connection to the server via a {{glossary('TCP handshake','TCP three-way handshake')}}. This mechanism is designed so that two entities attempting to communicate — in this case the browser and web server — can negotiate the parameters of the network TCP socket connection before transmitting data, often over {{glossary('HTTPS')}}. TCP's three-way handshaking technique is often referred to as "SYN-SYN-ACK" — or more accurately SYN, SYN-ACK, ACK — because there are three messages transmitted by TCP to negotiate and start a TCP session between two computers. Yes, this means three more messages back and forth between each server, and the request has yet to be made. ### TLS negotiation For secure connections established over HTTPS, another "handshake" is required. This handshake, or rather the {{glossary('TLS')}} negotiation, determines which cipher will be used to encrypt the communication, verifies the server, and establishes that a secure connection is in place before beginning the actual transfer of data. This requires five more round trips to the server before the request for content is actually sent. ![The DNS lookup, the TCP handshake, and 5 steps of the TLS handshake including clienthello, serverhello and certificate, clientkey and finished for both server and client.](ssl.jpg) While making the connection secure adds time to the page load, a secure connection is worth the latency expense, as the data transmitted between the browser and the web server cannot be decrypted by a third party. After the eight round trips to the server, the browser is finally able to make the request. ## Response Once we have an established connection to a web server, the browser sends an initial [HTTP `GET` request](/en-US/docs/Web/HTTP/Methods) on behalf of the user, which for websites is most often an HTML file. Once the server receives the request, it will reply with relevant response headers and the contents of the HTML. ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>My simple page</title> <link rel="stylesheet" href="styles.css" /> <script src="myscript.js"></script> </head> <body> <h1 class="heading">My Page</h1> <p>A paragraph with a <a href="https://example.com/about">link</a></p> <div> <img src="myimage.jpg" alt="image description" /> </div> <script src="anotherscript.js"></script> </body> </html> ``` This response for this initial request contains the first byte of data received. {{glossary('Time to First Byte')}} (TTFB) is the time between when the user made the request — say by clicking on a link — and the receipt of this first packet of HTML. The first chunk of content is usually 14KB of data. In our example above, the request is definitely less than 14KB, but the linked resources aren't requested until the browser encounters the links during parsing, described below. ### Congestion control / TCP slow start TCP packets are split into segments during transmission. Because TCP guarantees the sequence of packets, the server must receive an acknowledgment from the client in the form of an ACK packet after sending a certain number of segments. If the server waits for an ACK after each segment, that will result in frequent ACKs from the client and may increase transmission time, even in the case of a low-load network. On the other hand, sending too many segments at once can lead to the problem that in a busy network the client will not be able to receive the segments and will just keep responding with ACKs for a long time, and the server will have to keep re-sending the segments. In order to balance the number of transmitted segments, the {{glossary('TCP slow start')}} algorithm is used to gradually increase the amount of transmitted data until the maximum network bandwidth can be determined, and to reduce the amount of transmitted data in case of high network load. The number of segments to be transmitted is controlled by the value of the congestion window (CWND), which can be initialized to 1, 2, 4, or 10 MSS (MSS is 1500 bytes over the Ethernet protocol). That value is the number of bytes to send, upon receipt of which the client must send an ACK. If an ACK is received, then the CWND value will be doubled, and so the server will be able to send more segments the next time. If instead no ACK is received, then the CWND value will be halved. That mechanism thus achieves a balance between sending too many segments, and sending too few. ## Parsing Once the browser receives the first chunk of data, it can begin parsing the information received. {{glossary('parse', 'Parsing')}} is the step the browser takes to turn the data it receives over the network into the {{glossary('DOM')}} and {{glossary('CSSOM')}}, which is used by the renderer to paint a page to the screen. The DOM is the internal representation of the markup for the browser. The DOM is also exposed and can be manipulated through various APIs in JavaScript. Even if the requested page's HTML is larger than the initial 14KB packet, the browser will begin parsing and attempting to render an experience based on the data it has. This is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page — the CSS and HTML needed for the first render — in the first 14KB. But before anything is rendered to the screen, the HTML, CSS, and JavaScript have to be parsed. ### Building the DOM tree We describe five steps in the [critical rendering path](/en-US/docs/Web/Performance/Critical_rendering_path). The first step is processing the HTML markup and building the DOM tree. HTML parsing involves [tokenization](/en-US/docs/Web/API/DOMTokenList) and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree. The DOM tree describes the content of the document. The [`<html>`](/en-US/docs/Web/HTML/Element/html) element is the first element and root node of the document tree. The tree reflects the relationships and hierarchies between different elements. Elements nested within other elements are child nodes. The greater the number of DOM nodes, the longer it takes to construct the DOM tree. ![The DOM tree for our sample code, showing all the nodes, including text nodes.](dom.gif) When the parser finds non-blocking resources, such as an image, the browser will request those resources and continue parsing. Parsing can continue when a CSS file is encountered, but `<script>` elements — particularly those without an [`async`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) or `defer` attribute — block rendering, and pause the parsing of HTML. Though the browser's preload scanner hastens this process, excessive scripts can still be a significant bottleneck. ### Preload scanner While the browser builds the DOM tree, this process occupies the main thread. As this happens, the _preload scanner_ will parse through the content available and request high-priority resources like CSS, JavaScript, and web fonts. Thanks to the preload scanner, we don't have to wait until the parser finds a reference to an external resource to request it. It will retrieve resources in the background so that by the time the main HTML parser reaches the requested assets, they may already be in flight or have been downloaded. The optimizations the preload scanner provides reduce blockages. ```html <link rel="stylesheet" href="styles.css" /> <script src="myscript.js" async></script> <img src="myimage.jpg" alt="image description" /> <script src="anotherscript.js" async></script> ``` In this example, while the main thread is parsing the HTML and CSS, the preload scanner will find the scripts and image, and start downloading them as well. To ensure the script doesn't block the process, add the `async` attribute, or the `defer` attribute if JavaScript parsing and execution order is important. Waiting to obtain CSS doesn't block HTML parsing or downloading, but it does block JavaScript because JavaScript is often used to query CSS properties' impact on elements. ### Building the CSSOM tree The second step in the critical rendering path is processing CSS and building the CSSOM tree. The CSS object model is similar to the DOM. The DOM and CSSOM are both trees. They are independent data structures. The browser converts the CSS rules into a map of styles it can understand and work with. The browser goes through each rule set in the CSS, creating a tree of nodes with parent, child, and sibling relationships based on the CSS selectors. As with HTML, the browser needs to convert the received CSS rules into something it can work with. Hence, it repeats the HTML-to-object process, but for the CSS. The CSSOM tree includes styles from the user agent style sheet. The browser begins with the most general rule applicable to a node and recursively refines the computed styles by applying more specific rules. In other words, it cascades the property values. Building the CSSOM is very, very fast and is not displayed in a unique color in current developer tools. Rather, the "Recalculate Style" in developer tools shows the total time it takes to parse CSS, construct the CSSOM tree, and recursively calculate computed styles. In terms of web performance optimization, there are lower hanging fruit, as the total time to create the CSSOM is generally less than the time it takes for one DNS lookup. ### Other processes #### JavaScript compilation While the CSS is being parsed and the CSSOM created, other assets, including JavaScript files, are downloading (thanks to the preload scanner). JavaScript is parsed, compiled, and interpreted. The scripts are parsed into abstract syntax trees. Some browser engines take the [abstract syntax trees](https://en.wikipedia.org/wiki/Abstract_Syntax_Tree) and pass them into a compiler, outputting bytecode. This is known as JavaScript compilation. Most of the code is interpreted on the main thread, but there are exceptions such as code run in [web workers](/en-US/docs/Web/API/Web_Workers_API). #### Building the accessibility tree The browser also builds an [accessibility](/en-US/docs/Learn/Accessibility) tree that assistive devices use to parse and interpret content. The accessibility object model (AOM) is like a semantic version of the DOM. The browser updates the accessibility tree when the DOM is updated. The accessibility tree is not modifiable by assistive technologies themselves. Until the AOM is built, the content is not accessible to [screen readers](/en-US/docs/Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide). ## Render Rendering steps include style, layout, paint, and in some cases compositing. The CSSOM and DOM trees created in the parsing step are combined into a render tree which is then used to compute the layout of every visible element, which is then painted to the screen. In some cases, content can be promoted to its own layer and composited, improving performance by painting portions of the screen on the GPU instead of the CPU, freeing up the main thread. ### Style The third step in the critical rendering path is combining the DOM and CSSOM into a render tree. The computed style tree, or render tree, construction starts with the root of the DOM tree, traversing each visible node. Elements that aren't going to be displayed, like the [`<head>`](/en-US/docs/Web/HTML/Element/head) element and its children and any nodes with `display: none`, such as the `script { display: none; }` you will find in user agent stylesheets, are not included in the render tree as they will not appear in the rendered output. Nodes with `visibility: hidden` applied are included in the render tree, as they do take up space. As we have not given any directives to override the user agent default, the `script` node in our code example above will not be included in the render tree. Each visible node has its CSSOM rules applied to it. The render tree holds all the visible nodes with content and computed styles — matching up all the relevant styles to every visible node in the DOM tree, and determining, based on the [CSS cascade](/en-US/docs/Web/CSS/Cascade), what the computed styles are for each node. ### Layout The fourth step in the critical rendering path is running layout on the render tree to compute the geometry of each node. _Layout_ is the process by which the dimensions and location of all the nodes in the render tree are determined, plus the determination of the size and position of each object on the page. _Reflow_ is any subsequent size and position determination of any part of the page or the entire document. Once the render tree is built, layout commences. The render tree identified which nodes are displayed (even if invisible) along with their computed styles, but not the dimensions or location of each node. To determine the exact size and position of each object, the browser starts at the root of the render tree and traverses it. On the web page, almost everything is a box. Different devices and different desktop preferences mean an unlimited number of differing viewport sizes. In this phase, taking the viewport size into consideration, the browser determines what the sizes of all the different boxes are going to be on the screen. Taking the size of the viewport as its base, layout generally starts with the body, laying out the sizes of all the body's descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn't know the dimensions of, such as our image. The first time the size and position of each node is determined is called _layout_. Subsequent recalculations of are called _reflows_. In our example, suppose the initial layout occurs before the image is returned. Since we didn't declare the dimensions of our image, there will be a reflow once the image dimensions are known. ### Paint The last step in the critical rendering path is painting the individual nodes to the screen, the first occurrence of which is called the [first meaningful paint](/en-US/docs/Glossary/First_meaningful_paint). In the painting or rasterization phase, the browser converts each box calculated in the layout phase to actual pixels on the screen. Painting involves drawing every visual part of an element to the screen, including text, colors, borders, shadows, and replaced elements like buttons and images. The browser needs to do this super quickly. To ensure smooth scrolling and animation, everything occupying the main thread, including calculating styles, along with reflow and paint, must take the browser less than 16.67ms to accomplish. At 2048 x 1536, the iPad has over 3,145,000 pixels to be painted to the screen. That is a lot of pixels that have to be painted very quickly. To ensure repainting can be done even faster than the initial paint, the drawing to the screen is generally broken down into several layers. If this occurs, then compositing is necessary. Painting can break the elements in the layout tree into layers. Promoting content into layers on the GPU (instead of the main thread on the CPU) improves paint and repaint performance. There are specific properties and elements that instantiate a layer, including [`<video>`](/en-US/docs/Web/HTML/Element/video) and [`<canvas>`](/en-US/docs/Web/HTML/Element/canvas), and any element which has the CSS properties of [`opacity`](/en-US/docs/Web/CSS/opacity), a 3D [`transform`](/en-US/docs/Web/CSS/transform), [`will-change`](/en-US/docs/Web/CSS/will-change), and a few others. These nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons. Layers do improve performance but are expensive when it comes to memory management, so should not be overused as part of web performance optimization strategies. ### Compositing When sections of the document are drawn in different layers, overlapping each other, compositing is necessary to ensure they are drawn to the screen in the right order and the content is rendered correctly. As the page continues to load assets, reflows can happen (recall our example image that arrived late). A reflow sparks a repaint and a re-composite. Had we defined the dimensions of our image, no reflow would have been necessary, and only the layer that needed to be repainted would be repainted, and composited if necessary. But we didn't include the image dimensions! When the image is obtained from the server, the rendering process goes back to the layout steps and restarts from there. ## Interactivity Once the main thread is done painting the page, you would think we would be "all set." That isn't necessarily the case. If the load includes JavaScript, that was correctly deferred, and only executed after the [`onload`](/en-US/docs/Web/API/Window/load_event) event fires, the main thread might be busy, and not available for scrolling, touch, and other interactions. {{glossary('Time to Interactive')}} (TTI) is the measurement of how long it took from that first request which led to the DNS lookup and TCP connection to when the page is interactive — interactive being the point in time after the {{glossary('First Contentful Paint')}} when the page responds to user interactions within 50ms. If the main thread is occupied parsing, compiling, and executing JavaScript, it is not available and therefore not able to respond to user interactions in a timely (less than 50ms) fashion. In our example, maybe the image loaded quickly, but perhaps the `anotherscript.js` file was 2MB and our user's network connection was slow. In this case, the user would see the page super quickly, but wouldn't be able to scroll without jank until the script was downloaded, parsed, and executed. That is not a good user experience. Avoid occupying the main thread, as demonstrated in this WebPageTest example: ![The main thread is occupied by the downloading, parsing and execution of a JavaScript file - over a fast connection](visa_network.png) In this example, JavaScript execution took over 1.5 seconds, and the main thread was fully occupied that entire time, unresponsive to click events or screen taps. ## See also - [Web Performance](/en-US/docs/Web/Performance)
0
data/mdn-content/files/en-us/web/performance
data/mdn-content/files/en-us/web/performance/speculative_loading/index.md
--- title: Speculative loading slug: Web/Performance/Speculative_loading page-type: guide --- {{QuickLinksWithSubPages("Web/Performance")}} **Speculative loading** refers to the practice of performing navigation actions (such as DNS fetching, fetching resources, or rendering documents) before the associated pages are actually visited, based on predictions as to what pages the user is most likely to visit next. These predictions can be supplied by developers (for example, lists of the most popular destinations on their site) or determined by browser heuristics (for example based on popular sites in the user's history). When used successfully, such technologies can significantly improve performance by making pages available more quickly, or in some cases, instantly. This page reviews available speculative loading technologies and when they can and should be used to improve performance. ## Speculative loading mechanisms There are several mechanisms for speculative loading: - **Prefetching** involves fetching some or all of the resources required to render a document (or part of a document) before they are needed, so that when the time comes to render it, rendering can be achieved much more quickly. - **Prerendering** goes a step further, and actually renders the content ready to be shown when required. Depending on how this is done, this can result in an instant navigation from old page to new page. - **Preconnecting** involves speeding up future loads from a given origin by preemptively performing part or all of the connection handshake (i.e. DNS + TCP + TLS). > **Note:** The above descriptions are high-level and general. Exactly what browsers will do to achieve prefetching and prerendering depends on the features used. More exact feature descriptions are provided in the [Speculative loading features](#speculative_loading_features) section below. ## How is speculative loading achieved? Speculative loading is achieved in two main ways. First, some browsers will automatically prerender pages based on various heuristics to provide automatic performance improvements. Exactly how this is done depends on the browser implementation. Chrome, for example, automatically prerenders pages when matching strings are typed into the address bar — if it has a high confidence that you will visit that page (see [Viewing Chrome's address bar predictions](https://developer.chrome.com/blog/prerender-pages/#viewing-chromes-address-bar-predictions) for more details). In addition, it may automatically prerender search results pages when search terms are typed into the address bar, when instructed to do so by the search engine. It does this using the same mechanism as the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API). Second, there are several different platform features that developers can use to provide instructions on what speculative loading they want the browser to perform. These are reviewed in the next section. ## Speculative loading features ### `<link rel="preconnect">` [`<link rel="preconnect">`](/en-US/docs/Web/HTML/Attributes/rel/preconnect) provides a hint to browsers that the user is likely to need resources from the specified resource's origin, and therefore the browser can likely improve performance by preemptively initiating a connection to that origin. Supporting browsers will preemptively perform part or all of the connection handshake (i.e. DNS + TCP + TLS). For example: ```html <link rel="preconnect" href="https://example.com" /> ``` `<link rel="preconnect">` is widely supported across browsers, and will provide a benefit to any future cross-origin HTTP request, navigation or subresource. It has no benefit on same-origin requests because the connection is already open. If a page needs to make connections to many third-party domains, preconnecting them all can be counterproductive. The `<link rel="preconnect">` hint is best used for only the most critical connections. For the others, just use `<link rel="dns-prefetch">` to save time on the first step — the DNS lookup. You can also implement preconnect as an HTTP [Link](/en-US/docs/Web/HTTP/Headers/Link) header, for example: ```http Link: <https://example.com>; rel="preconnect" ``` ### `<link rel="dns-prefetch">` [`<link rel="dns-prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/dns-prefetch) provides a hint to browsers that the user is likely to need resources from the specified resource's origin, and therefore the browser may be able to improve performance by preemptively performing DNS resolution for that origin. It is identical to `<link rel="preconnect">` except that it only handles the DNS part. Again, browser support is widespread, and it has no benefit on same-origin requests because the connection is already open. For example: ```html <link rel="dns-prefetch" href="https://example.com" /> ``` > **Note:** See [Using dns-prefetch](/en-US/docs/Web/Performance/dns-prefetch) for more details. ### `<link rel="preload">` [`<link rel="preload">`](/en-US/docs/Web/HTML/Attributes/rel/preload) provides a hint to browsers as to what resources are high-priority on _the current page_, so it can start downloading them early when it sees the {{htmlelement("link")}} element(s) in the {{htmlelement("head")}} of the page. For example: ```html <link rel="preload" href="main.js" as="script" /> <!-- CORS-enabled preload --> <link rel="preload" href="https://www.example.com/fonts/cicle_fina-webfont.woff2" as="font" type="font/woff2" crossorigin /> ``` The result is kept in a per-document in-memory cache. If you preload something your current page doesn't use as a subresource, it is generally a waste of resources, although the result may populate the HTTP cache if headers allow. You can also implement preload as an HTTP [Link](/en-US/docs/Web/HTTP/Headers/Link) header, for example: ```http Link: <https://www.example.com/fonts/cicle_fina-webfont.woff2>; rel="preload" ``` Browser support for `<link rel="preload">`/`<link rel="modulepreload">` is widespread in modern browsers. ### `<link rel="modulepreload">` [`<link rel="modulepreload">`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload) provides a hint to browsers as to what JavaScript modules are high-priority on _the current page_, so it can start downloading them early. For example: ```js <link rel="modulepreload" href="main.js" /> ``` It is a specialized version of `<link rel="preload">` for [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) and works basically the same way. However, there are some differences: - The browser knows the resource is a JavaScript module, as the `as` attribute is not needed, and it can use the correct credentials modes to avoid double-fetching. - Rather than just downloading it and storing it in a cache, the browser downloads it, then parses and compiles it directly into the in-memory module map. - The browser can also do the same for module dependencies automatically. ### `<link rel="prefetch">` [`<link rel="prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/prefetch) provides a hint to browsers that the user is likely to need the target resource for future navigations, and therefore the browser can likely improve the user experience by preemptively fetching and caching the resource. `<link rel="prefetch">` is used for same-site navigation resources, or for subresources used by same-site pages. For example: ```js <link rel="prefetch" href="main.js" /> ``` Prefetching can be used to fetch both HTML and sub-resources for a possible next navigation. A common use case is to have a simple website landing page that fetches more "heavy-weight" resources used by the rest of the site. ```html <link rel="prefetch" href="/app/style.css" /> <link rel="prefetch" href="/landing-page" /> ``` The result is kept in the HTTP cache on disk. Because of this it is useful for prefetching subresources, even if they are not used by the current page. You could also use it to prefetch the next document the user will likely visit on the site. However, as a result you need to be careful with headers — for example certain [Cache-Control](/en-US/docs/Web/HTTP/Headers/Cache-Control) headers could block prefetching (for example `no-cache` or `no-store`). Many browsers now implement some form of [cache partitioning](https://developer.chrome.com/en/blog/http-cache-partitioning/), which makes `<link rel="prefetch">` useless for resources intended for use by different top-level sites. This includes the main document when navigating cross-site. So, for example, the following prefetch: ```html <link rel="prefetch" href="https://news.example/article" /> ``` Would not be accessible from `https://aggregator.example/`. > **Note:** `<link rel="prefetch">` is functionally equivalent to a {{domxref("fetch()")}} call with a `priority: "low"` option set on it, except that the former will generally have an even lower priority, and it will have a [`Sec-Purpose: prefetch`](/en-US/docs/Web/HTTP/Headers/Sec-Purpose) header set on the request. > **Note:** The fetch request for a `prefetch` operation results in an HTTP Request that includes the HTTP header [`Sec-Purpose: prefetch`](/en-US/docs/Web/HTTP/Headers/Sec-Purpose). A server might use this header to change the cache timeouts for the resources, or perform other special handling. > The request will also include the {{HTTPHeader("Sec-Fetch-Dest")}} header with the value set to `empty`. > The {{HTTPHeader("Accept")}} header in the request will match the value used for normal navigation requests. This allows the browser to find the matching cached resources following navigation. > If a response is returned, it gets cached with the request in the HTTP cache. ### `<link rel="prerender">` {{deprecated_inline}}{{non-standard_inline}} > **Note:** This technology was only ever available in Chrome, and is now deprecated. You should use the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) instead, which supercedes this. [`<link rel="prerender">`](/en-US/docs/Web/HTML/Attributes/rel/prerender) provides a hint to browsers that the user might need the target resource for the next navigation, and therefore the browser can likely improve performance by prerendering the resource. `prerender` is used for future navigations, same-site only, and as such makes sense for multi-page applications (MPAs), not single-page applications (SPAs). For example: ```html <link rel="prerender" href="/next-page" /> ``` It will fetch the referenced document, then fetch any linked resources that are statically findable and fetch them too, storing the result in the HTTP cache on disk with a five-minute timeout. The exception is subresources loaded via JavaScript — it does not find these. It has other problems too — like `<link rel="prefetch">` it can also be blocked by [Cache-Control](/en-US/docs/Web/HTTP/Headers/Cache-Control) headers, and be rendered useless for resources intended for use by different top-level sites by browser [cache partitioning](https://developer.chrome.com/en/blog/http-cache-partitioning/). ### Speculation Rules API [`<script type="speculationrules">`](/en-US/docs/Web/HTML/Element/script/type/speculationrules) is used to provide a set of rules that determine what future documents should be prefetched or prerendered by the browser. This is part of the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API). ## When should you use each feature? The following table summarizes the features detailed above, and provides guidance on when to use each one. | Speculative loading features | Purpose | When to use | | --------------------------------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`<link rel="preconnect">`](/en-US/docs/Web/HTML/Attributes/rel/preconnect) | Cross-origin connection warming | Use on your most critical cross-origin connections to provide performance improvements when connecting to them. | | [`<link rel="dns-prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/dns-prefetch) | Cross-origin connection warming | Use on all of your cross-origin connections to provide small performance improvements when connecting to them. | | [`<link rel="preload">`](/en-US/docs/Web/HTML/Attributes/rel/preload) | High-priority loading of current page subresources | Use to load high-priority resources faster on the current page, for strategic performance improvements. Don't preload everything, otherwise you won't see the benefit. Also has some other interesting uses — see [Preload: What Is It Good For?](https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/) on Smashing Magazine (2016) | | [`<link rel="modulepreload">`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload) | High-priority loading of current page JavaScript modules | Use to preload high-priority JavaScript modules for strategic performance improvements. | | [`<link rel="prefetch">`](/en-US/docs/Web/HTML/Attributes/rel/prefetch) | Pre-populating the HTTP cache | Use to prefetch same-site future navigation resources or subresources used on those pages. Uses HTTP cache therefore has a number of issues with document prefetches, such as being potentially blocked by [Cache-Control](/en-US/docs/Web/HTTP/Headers/Cache-Control) headers. Use the [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) for document prefetches instead, where it is supported. | | [`<link rel="prerender">`](/en-US/docs/Web/HTML/Attributes/rel/prerender) | Preparing for the next navigation | Deprecated; you are advised not to use this. Use [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) prerender instead, where it is supported. | | [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) prefetch | Preparing for the next navigation | Use to prefetch same or cross-site future navigation documents. Broad adoption is recommended, where it is supported; check to make sure the pages are [safe to prefetch](/en-US/docs/Web/API/Speculation_Rules_API#unsafe_prefetching). It doesn't handle subresource prefetches; for that you'll need to use `<link rel="prefetch">`. | | [Speculation Rules API](/en-US/docs/Web/API/Speculation_Rules_API) prerender | Preparing for the next navigation | Use to preload same-origin future navigation resources, for near-instant navigations. Use on high-priority pages, where it is supported; check to make sure the pages are [safe to prerender](/en-US/docs/Web/API/Speculation_Rules_API#unsafe_prerendering). | ## See also - [Prerender pages in Chrome for instant page navigations](https://developer.chrome.com/blog/prerender-pages/) on developer.chrome.com (2023)
0
data/mdn-content/files/en-us/web
data/mdn-content/files/en-us/web/xslt/index.md
--- title: "XSLT: Extensible Stylesheet Language Transformations" slug: Web/XSLT page-type: landing-page --- {{XsltSidebar}} **Extensible Stylesheet Language Transformations (XSLT)** is an [XML](/en-US/docs/Web/XML/XML_introduction)-based language used, in conjunction with specialized processing software, for the transformation of XML documents. Although the process is referred to as "transformation," the original document is not changed; rather, a new XML document is created based on the content of an existing document. Then, the new document may be serialized (output) by the processor in standard XML syntax or in another format, such as [HTML](/en-US/docs/Web/HTML) or plain text. XSLT is most often used to convert data between different XML schemas or to convert XML data into web pages or PDF documents. ## Documentation - [XSLT Element Reference](/en-US/docs/Web/XSLT/Element) - : Reference. - [Transforming XML with XSLT](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT) - : XSLT allows a stylesheet author to transform a primary XML document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format. - [Specifying parameters using processing instructions](/en-US/docs/Web/XSLT/PI_Parameters) - : Firefox allows stylesheet parameters to be specified when using the `<?xml-stylesheet?>` processing instruction. This is done using the `<?xslt-param?>` PI described in this document. - [XSLT Tutorial](https://www.w3schools.com/xml/xsl_intro.asp) - : This [W3Schools](https://www.w3schools.com) tutorial teaches the reader how to use XSLT to transform XML documents into other formats, like XHTML. - [What is XSLT?](https://www.xml.com/pub/a/2000/08/holman/) - : This extensive introduction to XSLT and XPath assumes no prior knowledge of the technologies and guides the reader through background, context, structure, concepts and introductory terminology. - [Common XSLT Errors](/en-US/docs/Web/XSLT/Common_errors) - : This article lists some common problems using XSLT in Firefox. ## Related Topics - [XML](/en-US/docs/Web/XML/XML_introduction), [XPath](/en-US/docs/Web/XPath)
0
data/mdn-content/files/en-us/web/xslt
data/mdn-content/files/en-us/web/xslt/element/index.md
--- title: XSLT elements reference slug: Web/XSLT/Element page-type: landing-page --- {{XsltSidebar}} There are two types of elements discussed here: top-level elements and instructions. A top-level element must appear as the child of either `<xsl:stylesheet>` or `<xsl:transform>`. An instruction, on the other hand, is associated with a template. A stylesheet may include several templates. A third type of element, not discussed here, is the literal result element (LRE). An LRE also appears in a template. It consists of any non-instruction element that should be copied as-is to the result document, for example, an `<hr>` element in an HTML conversion stylesheet. On a related note, any attribute in an LRE and some attributes of a limited number of XSLT elements can also include what is known as an attribute value template. An attribute value template is a string that includes an embedded XPath expression which is used to specify the value of an attribute. At run-time the expression is evaluated and the result of the evaluation is substituted for the XPath expression. For example, assume that a variable "`image-dir`" is defined as follows: ```xml <xsl:variable name="image-dir">/images</xsl:variable> ``` The expression to be evaluated is placed inside curly braces: ```xml <img src="{$image-dir}/mygraphic.jpg"/> ``` This would result in the following: ```xml <img src="/images/mygraphic.jpg"/> ``` The element annotations that follow include a description, a syntax listing, a list of required and optional attributes, a description of type and position, its source in the W3C Recommendation and an explanation of the degree of present Gecko support. - [`<xsl:apply-imports>`](/en-US/docs/Web/XSLT/Element/apply-imports) - [`<xsl:apply-templates>`](/en-US/docs/Web/XSLT/Element/apply-templates) - [`<xsl:attribute>`](/en-US/docs/Web/XSLT/Element/attribute) - [`<xsl:attribute-set>`](/en-US/docs/Web/XSLT/Element/attribute-set) - [`<xsl:call-template>`](/en-US/docs/Web/XSLT/Element/call-template) - [`<xsl:choose>`](/en-US/docs/Web/XSLT/Element/choose) - [`<xsl:comment>`](/en-US/docs/Web/XSLT/Element/comment) - [`<xsl:copy>`](/en-US/docs/Web/XSLT/Element/copy) - [`<xsl:copy-of>`](/en-US/docs/Web/XSLT/Element/copy-of) - [`<xsl:decimal-format>`](/en-US/docs/Web/XSLT/Element/decimal-format) - [`<xsl:element>`](/en-US/docs/Web/XSLT/Element/element) - [`<xsl:fallback>`](/en-US/docs/Web/XSLT/Element/fallback) _(not supported)_ - [`<xsl:for-each>`](/en-US/docs/Web/XSLT/Element/for-each) - [`<xsl:if>`](/en-US/docs/Web/XSLT/Element/if) - [`<xsl:import>`](/en-US/docs/Web/XSLT/Element/import) _(mostly supported)_ - [`<xsl:include>`](/en-US/docs/Web/XSLT/Element/include) - [`<xsl:key>`](/en-US/docs/Web/XSLT/Element/key) - [`<xsl:message>`](/en-US/docs/Web/XSLT/Element/message) - [`<xsl:namespace-alias>`](/en-US/docs/Web/XSLT/Element/namespace-alias) _(not supported)_ - [`<xsl:number>`](/en-US/docs/Web/XSLT/Element/number) _(partially supported)_ - [`<xsl:otherwise>`](/en-US/docs/Web/XSLT/Element/otherwise) - [`<xsl:output>`](/en-US/docs/Web/XSLT/Element/output) _(partially supported)_ - [`<xsl:param>`](/en-US/docs/Web/XSLT/Element/param) - [`<xsl:preserve-space>`](/en-US/docs/Web/XSLT/Element/preserve-space) - [`<xsl:processing-instruction>`](/en-US/docs/Web/XSLT/Element/processing-instruction) - [`<xsl:sort>`](/en-US/docs/Web/XSLT/Element/sort) - [`<xsl:strip-space>`](/en-US/docs/Web/XSLT/Element/strip-space) - [`<xsl:stylesheet>`](/en-US/docs/Web/XSLT/Element/stylesheet) _(partially supported)_ - [`<xsl:template>`](/en-US/docs/Web/XSLT/Element/template) - [`<xsl:text>`](/en-US/docs/Web/XSLT/Element/text) _(partially supported)_ - [`<xsl:transform>`](/en-US/docs/Web/XSLT/Element/transform) - [`<xsl:value-of>`](/en-US/docs/Web/XSLT/Element/value-of) _(partially supported)_ - [`<xsl:variable>`](/en-US/docs/Web/XSLT/Element/variable) - [`<xsl:when>`](/en-US/docs/Web/XSLT/Element/when) - [`<xsl:with-param>`](/en-US/docs/Web/XSLT/Element/with-param)
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/attribute-set/index.md
--- title: <xsl:attribute-set> slug: Web/XSLT/Element/attribute-set page-type: xslt-element --- {{XsltSidebar}} The `<xsl:attribute-set>` element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in CSS. ### Syntax ```xml <xsl:attribute-set name=NAME use-attribute-sets=LIST-OF-NAMES> <xsl:attribute> </xsl:attribute-set> ``` ### Required Attributes - `name` - : Specifies the name of the attribute set. The name must be a valid QName. ### Optional Attributes - `use-attribute-sets` - : Builds an attribute set from other attribute sets. The names of the contributing sets must be separated with whitespace characters and must not directly or indirectly embed themselves. ### Type Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 7.1.4. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/strip-space/index.md
--- title: <xsl:strip-space> slug: Web/XSLT/Element/strip-space page-type: xslt-element --- {{XsltSidebar}} The `<xsl:strip-space>` element defines the elements in the source document for which whitespace should be removed. ### Syntax ```xml <xsl:strip-space elements=LIST-OF-ELEMENT-NAMES /> ``` ### Required Attributes - `elements` - : Specifies a space-separated list of elements in the source whose whitespace-only text nodes should be removed. ### Optional Attributes None. ### Type Top-level, must be a child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 3.4 ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/processing-instruction/index.md
--- title: <xsl:processing-instruction> slug: Web/XSLT/Element/processing-instruction page-type: xslt-element --- {{XsltSidebar}} The `<xsl:processing-instruction>` element writes a processing instruction to the output document. ### Syntax `<xsl:processing-instruction name=NAME> TEMPLATE </xsl:processing-instruction>` ### Required Attributes - `name` - : Specifies the name of this processing instruction. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 7.3 ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/stylesheet/index.md
--- title: <xsl:stylesheet> slug: Web/XSLT/Element/stylesheet page-type: xslt-element spec-urls: https://www.w3.org/TR/xslt-30/#stylesheet-element --- {{XsltSidebar}} The `<xsl:stylesheet>` element (or the equivalent `<xsl:transform>` element) is the outermost element of a stylesheet. ### Namespace Declaration A pseudo-attribute required to identify the document as an XSLT stylesheet. Typically this is `xmlns:xsl="http://www.w3.org/1999/XSL/Transform"`. ## Syntax ```xml <xsl:stylesheet version="NUMBER" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" id="NAME" extension-element-prefixes="LIST-OF-NAMES" exclude-result-prefixes="LIST-OF-NAMES"> ENTIRE STYLESHEET </xsl:stylesheet> ``` ### Required Attributes - `version` - : Specifies the version of XSLT required by this stylesheet. ### Optional Attributes - `exclude-result-prefixes` - : Specifies any namespace used in this document that should not be sent to the output document. The list is whitespace separated. - `extension-element-prefixes` - : Specifies a space-separated list of any namespace prefixes for extension elements in this document. - `default-collation` - : Specifies the default collation used by all {{Glossary("XPath")}} expressions appearing in attributes or text value templates that have the element as an ancestor, unless overridden by another `default-collation` attribute on an inner element. It also determines the collation used by certain XSLT constructs (such as [`<xsl:key>`](/en-US/docs/Web/XSLT/Element/key) and [`<xsl:for-each-group>`](/en-US/docs/Web/XSLT/Element/for-each-group)) within its scope. - `default-mode` - : Defines the default value for the `mode` attribute of all [`<xsl:template>`](/en-US/docs/Web/XSLT/Element/template) and [`<xsl:apply-templates>`](/en-US/docs/Web/XSLT/Element/apply-templates) elements within its scope. - `default-validation` - : Defines the default value of the `validation` attribute of all relevant instructions appearing within its scope. - `expand-text` - : Determines whether descendant text nodes of the element are treated as text value templates. - `id` - : Specifies an `id` for this stylesheet. This is most often used when the stylesheet is embedded in another XML document. - `input-type-annotations` - : Specifies whether type annotations are stripped from the element so the same results are produced whether the source documents have been validated against a schema or not. - `use-when` - : Determines whether the element and all the nodes that have it as ancestor are excluded from the stylesheet. - `xpath-default-namespace` - : Specifies the namespace that will be used if the element name is unprefixed or an unprefixed type name within an XPath expression. ### Type Required outermost element of stylesheet. ## Specifications {{Specifications}}
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/if/index.md
--- title: <xsl:if> slug: Web/XSLT/Element/if page-type: xslt-element --- {{XsltSidebar}} The `<xsl:if>` element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the `<xsl:choose>` element with one `<xsl:when>` and one `<xsl:otherwise>` children. ### Syntax ```xml <xsl:if test=EXPRESSION> TEMPLATE </xsl:if> ``` ### Required Attributes - `test` - : Contains an XPath expression that can be evaluated (using the rules defined for `boolean( )` if necessary) to a Boolean value. If the value is true, the template is processed; if it is not, no action is taken. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSL section 9.1. ### Gecko support Supported
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/preserve-space/index.md
--- title: <xsl:preserve-space> slug: Web/XSLT/Element/preserve-space page-type: xslt-element --- {{XsltSidebar}} The `<xsl:preserve-space>` element defines the elements in the source document for which whitespace should be preserved. If there is more than one element, separate the names with a whitespace character. Preserving whitespace is the default setting, so this element only needs to be used to counteract an `<xsl:strip-space>` element. ### Syntax ```xml <xsl:preserve-space elements=LIST-OF-ELEMENT-NAMES /> ``` ### Required Attributes - `elements` - : Specifies the elements for which whitespace should be preserved. ### Optional Attributes None. ### Type Top-level, must be a child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 3.4 ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/variable/index.md
--- title: <xsl:variable> slug: Web/XSLT/Element/variable page-type: xslt-element --- {{XsltSidebar}} The `<xsl:variable>` element declares a global or local variable in a stylesheet and gives it a value. Because XSLT permits no side-effects, once the value of the variable has been established, it remains the same until the variable goes out of scope ### Syntax ```xml <xsl:variable name=NAME select=EXPRESSION > TEMPLATE </xsl:variable> ``` ### Required Attributes - `name` - : Gives the variable a name. ### Optional Attributes - `select` - : Defines the value of the variable through an XPath expression. If the element contains a template, this attribute is ignored. ### Type Top-level or instruction. If it occurs as a top-level element, the variable is global in scope, and can be accessed throughout the document. If it occurs within a template, the variable is local in scope, accessible only within the template in which it appears. ### Defined XSLT, section 11. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/element/index.md
--- title: <xsl:element> slug: Web/XSLT/Element/element page-type: xslt-element --- {{XsltSidebar}} The `<xsl:element>` element creates an element in the output document. ### Syntax ```xml <xsl:element name=NAME namespace=URI use-attribute-sets=LIST-OF-NAMES > TEMPLATE </xsl:element> ``` ### Required Attributes - `name` - : Specifies the desired name of the output element. The name must be a valid QName. ### Optional Attributes - `namespace` - : Specifies the namespace of the output element. - `use-attribute-sets` - : A whitespace‐separated list of [`attribute-set` element](/en-US/docs/Web/XSLT/Element/attribute-set) names to be applied to the `element` element's output element. Applied attributes can be overridden via nested `attribute` elements. ### Type Instruction, appears within a template. ### Defined XSLT, section 7.1.2. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/when/index.md
--- title: <xsl:when> slug: Web/XSLT/Element/when page-type: xslt-element --- {{XsltSidebar}} The `<xsl:when>` element always appears within an `<xsl:choose>` element, acting like a case statement. ### Syntax ```xml <xsl:when test=EXPRESSION> TEMPLATE </xsl:when> ``` ### Required Attributes - `test` - : Specifies a boolean expression to be evaluated. If true, the contents of the element are processed; if false, they are ignored. ### Optional Attributes None. ### Type Subinstruction, always appears within an `<xsl:choose>` element. ### Defined XSLT, section 9.2. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/template/index.md
--- title: <xsl:template> slug: Web/XSLT/Element/template page-type: xslt-element --- {{XsltSidebar}} The `<xsl:template>` element defines an output producing template. This element must have either the match attribute or the name attribute set. ### Syntax ```xml <xsl:template match=PATTERN name=NAME mode=NAME priority=NUMBER> <xsl:param> [optional] TEMPLATE </xsl:template> ``` ### Required Attributes None. ### Optional Attributes - `match` - : Specifies a pattern that determines the elements for which this template should be used. It is a required attribute if there is no `name` attribute. - `name` - : Specifies a name for this template, by which it can be invoked through the `<xsl:call-template>` element. - `mode` - : Specifies a particular mode for this template, which can be matched by an attribute of the `<xsl:apply-templates>` element. This is useful for processing the same information in multiple ways. - `priority` - : Specifies a numeric priority for this template. This can be any number other than `Infinity`. The processor uses this number when more than one template matches the same node. ### Type Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 5.3. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/include/index.md
--- title: <xsl:include> slug: Web/XSLT/Element/include page-type: xslt-element --- {{XsltSidebar}} The `<xsl:include>` element merges the contents of one stylesheet with another. Unlike the case of `<xsl:import>`, the contents of an included stylesheet have exactly the same precedence as the contents of the including stylesheet. ### Syntax ```xml <xsl:include href=URI /> ``` ### Required Attributes - `href` - : Specifies the URI of the stylesheet to include. ### Optional Attributes None. ### Type Top-level, may appear in any order as a child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 2.6.1. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/transform/index.md
--- title: <xsl:transform> slug: Web/XSLT/Element/transform page-type: xslt-element --- {{XsltSidebar}} The `<xsl:transform>` element is exactly equivalent to the [`<xsl:stylesheet>`](/en-US/docs/Web/XSLT/Element/stylesheet) element. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/import/index.md
--- title: <xsl:import> slug: Web/XSLT/Element/import page-type: xslt-element --- {{XsltSidebar}} The `<xsl:import>` element is a top-level element that serves to import the contents of one stylesheet into another stylesheet. Generally speaking, the contents of the imported stylesheet have a lower import precedence than that of the importing stylesheet. This is in contrast to `<xsl:include>` where the contents of the included stylesheet have exactly the same precedence as the contents of the including stylesheet. ### Syntax ```xml <xsl:import href=URI /> ``` ### Required Attributes - `href` - : Specifies the URI of the stylesheet to import. ### Optional Attributes None. ### Type Top-level, must appear before any other child of `<xsl:stylesheet>` or `<xsl:transform>` in the importing stylesheet. ### Defined XSLT, section 2.6.2. ### Gecko support Mostly supported with a few issues with top level variables and parameters as of Mozilla 1.0.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/comment/index.md
--- title: <xsl:comment> slug: Web/XSLT/Element/comment page-type: xslt-element --- {{XsltSidebar}} The `<xsl:comment>` element writes a comment to the output document. It must include only text. ### Syntax ```xml <xsl:comment> TEMPLATE </xsl:comment> ``` ### Required Attributes None. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 7.4. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/output/index.md
--- title: <xsl:output> slug: Web/XSLT/Element/output page-type: xslt-element --- {{XsltSidebar}} The `<xsl:output>` element controls the characteristics of the output document. To function correctly in Netscape, this element, with the method attribute, must be used. As of 7.0, `method="text"` works as expected. ### Syntax ```xml <xsl:output method="xml" | "html" | "text" version=STRING encoding=STRING omit-xml-declaration="yes" | "no" standalone="yes" | "no" doctype-public=STRING doctype-system=STRING cdata-section-elements=LIST-OF-NAMES indent="yes" | "no" media-type=STRING /> ``` ### Required Attributes None. ### Optional Attributes - `method` - : Specifies output format. - `version` - : Specifies the value of the version attribute of the XML or HTML declaration in the output document. This attribute is only used when `method="html"` or `method="xml"`. - `encoding` - : Specifies the value of the `encoding` attribute in the output document. - `omit-xml-declaration` - : Indicates whether or not to include an XML declaration in the output. Acceptable values are "`yes`" or "`no`". - `standalone` (Not supported.) - : If present, indicates that a standalone declaration should occur in the output document and gives its value. Acceptable values are "yes" or "no". - `doctype-public` - : Specifies the value of the `PUBLIC` attribute of the `DOCTYPE` declaration in the output document. - `doctype-system` - : Specifies the value of the `SYSTEM` attribute of the `DOCTYPE` declaration in the output document. - `cdata-section-elements` - : Lists elements whose text contents should be written as `CDATA` sections. Elements should be whitespace separated. - `indent` (Not supported.) - : Specifies if the output should be indented to indicate its hierarchic structure. - `media-type` (Not supported.) - : Specifies the output document MIME type. ### Type Top-level, must be the child `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 16. ### Gecko support Partial support. See comments above.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/apply-templates/index.md
--- title: <xsl:apply-templates> slug: Web/XSLT/Element/apply-templates page-type: xslt-element --- {{XsltSidebar}} The `<xsl:apply-templates>` element selects a set of nodes in the input tree and instructs the processor to apply the proper templates to them. ### Syntax ```xml <xsl:apply-templates select=EXPRESSION mode=NAME> <xsl:with-param> [optional] <xsl:sort> [optional] </xsl:apply-templates> ``` ### Required Attributes None. ### Optional Attributes - `select` - : Uses an XPath expression that specifies the nodes to be processed. An asterisk(`*`) selects the entire node-set. If this attribute is not set, all child nodes of the current node are selected. - `mode` - : If there are multiple ways of processing defined for the same node, distinguishes among them. ### Type Instruction, appears within a template. ### Defined XSLT section 5.4. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/namespace-alias/index.md
--- title: <xsl:namespace-alias> slug: Web/XSLT/Element/namespace-alias page-type: xslt-element --- {{XsltSidebar}} The `<xsl:namespace-alias>` element is a rarely used device that maps a namespace in the stylesheet to a different namespace in the output tree. The most common use for this element is in generating a stylesheet from another stylesheet. To prevent a normally `xsl:`-prefixed literal result element (which should be copied as-is to the result tree) from being misunderstood by the processor, it is assigned a temporary namespace which is appropriately re-converted back to the XSLT namespace in the output tree. ### Syntax ```xml <xsl:namespace-alias stylesheet-prefix=NAME result-prefix=NAME /> ``` ### Required Attributes - `stylesheet-prefix` - : Specifies the temporary namespace. - `result-prefix` - : Specifies the desired namespace for the output tree. ### Optional Attributes None. ### Type Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 7.1.1 ### Gecko support Not supported at this time.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/copy-of/index.md
--- title: <xsl:copy-of> slug: Web/XSLT/Element/copy-of page-type: xslt-element --- {{XsltSidebar}} The `<xsl:copy-of>` element makes a deep copy (including descendant nodes) of whatever the select attribute specifies to the output document. ### Syntax ```xml <xsl:copy-of select=EXPRESSION /> ``` ### Required Attributes - `select` - : Uses an XPath expression that specifies what is to be copied. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 11.3. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/apply-imports/index.md
--- title: <xsl:apply-imports> slug: Web/XSLT/Element/apply-imports page-type: xslt-element --- {{XsltSidebar}} The `<xsl:apply-imports>` element is fairly arcane, used mostly in complex stylesheets. Import precedence requires that template rules in main stylesheets have higher precedence than template rules in imported stylesheets. Sometimes, however, it is useful to be able to force the processor to use a template rule from the (lower precedence) imported stylesheet rather than an equivalent rule in the main stylesheet. ### Syntax ```xml <xsl:apply-imports/> ``` ### Required Attributes None. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 5.6. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/text/index.md
--- title: <xsl:text> slug: Web/XSLT/Element/text page-type: xslt-element --- {{XsltSidebar}} The `<xsl:text>` element writes literal text to the output tree. It may contain `#PCDATA`, literal text, and entity references. ### Syntax ```xml <xsl:text disable-output-escaping="yes" | "no"> TEXT </xsl:text> ``` ### Required Attributes None. ### Optional Attributes - `disable-output-escaping` (Netscape does not serialize the result of transformation - the "output" below - so this attribute is essentially irrelevant in context. To output html-entities, use numerical values instead, eg `&#160;` for `&nbsp;`) - : Specifies whether special characters are escaped when written to the output. The available values are "`yes`" or "`no`". If "`yes`" is set, for example, the character `>` is output as `>`, not as `&gt;`. ### Type Instruction, appears within a template. ### Defined XSLT, section 7.2 ### Gecko support Supported as noted.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/number/index.md
--- title: <xsl:number> slug: Web/XSLT/Element/number page-type: xslt-element --- {{XsltSidebar}} The `<xsl:number>` element counts things sequentially. It can also be used to quickly format a number. ### Syntax ```xml <xsl:number count=EXPRESSION level="single" | "multiple" | "any" from=EXPRESSION value=EXPRESSION format=FORMAT-STRING lang=XML:LANG-CODE letter-value="alphabetic" | "traditional" grouping-separator=CHARACTER grouping-size=NUMBER /> ``` ### Required Attributes None. ### Optional Attributes - `count` - : Specifies what in the source tree should be numbered sequentially. It uses an XPath expression. - `level` - : Defines how levels of the source tree should be considered in generating sequential numbers. It has three valid values: `single`, `multiple`, and `any`. The default value is `single`: - `single` - : Numbers sibling nodes sequentially, as in the items in a list. The processor goes to the first node in the [`ancestor-or-self`](/en-US/docs/Web/XPath/Axes#ancestor-or-self) axis that matches the `count` attribute and then counts that node plus all its preceding siblings (stopping when it reaches a match to the `from` attribute, if there is one) that also match the `count` attribute. If no match is found, the sequence will be an empty list. - `multiple` - : Numbers nodes as a composite sequence that reflects the hierarchic position of the node, e.g. 1.2.2.5. (The nested format can be specified with the `format` attribute, e.g. A.1.1). The processor looks at all [`ancestors`](/en-US/docs/Web/XPath/Axes#ancestor) of the current node and the current node itself, stopping when it reaches a match for the `from` attribute, if there is one. For each node in this list that matches the `count` attribute, the processor counts how many preceding matching siblings it has, and adds one for the node itself. If no match is found, the sequence will be an empty list. - `any` (Not supported at this time.) - : Numbers all matching nodes, regardless of level, sequentially. The [`ancestor`](/en-US/docs/Web/XPath/Axes#ancestor), [`self`](/en-US/docs/Web/XPath/Axes#self), and [`preceding`](/en-US/docs/Web/XPath/Axes#preceding) axes are all considered. The processor starts at the current node and proceeds in reverse document order, stopping if it reaches a match to any `from` attribute. If no match to the `count` attribute is found, the sequence will be an empty list. This level is not supported at this time. - `from` - : Specifies where the numbering should start or start over. The sequence begins with the first descendant of the node that matches the `from` attribute. - `value` - : Applies a given format to a number. This is a quick way to format a user-supplied number (as opposed to a node sequence number) in any of the standard `<xsl:number>` formats. - `format` - : Defines the format of the generated number: - `format="1"` - : `1 2 3 . . .` (This is the only format supported at this time) - `format="01"` - : `01 02 03 . . . 09 10 11 . . .` - `format="a"` - : `a b c . . .y z aa ab . . .` - `format="A"` - : `A B C . . . Y Z AA AB . . .` - `format="i"` - : `i ii iii iv v . . .` - `format="I"` - : `I II III IV V . . .` - `lang` (Not supported at this time.) - : Specifies which language's alphabet should be used in letter-based numbering formats. - `letter-value` - : Disambiguates between numbering sequences that use letters. Some languages have more than one numbering system that use letters. If both systems begin with the same token, ambiguity can arise. This attribute can have the value "`alphabetic`" or "`traditional`". The default is "`alphabetic`". - `grouping-separator` - : Specifies what character should be used as the group (e.g. thousands) separator. The default is the comma (`,`). - `grouping-size` - : Indicates the number of digits that make up a numeric group. The default value is "`3`". ### Type Instruction, appears within a template. ### Defined XSLT, section 7.7 ### Gecko support Partial support. See comments above.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/message/index.md
--- title: <xsl:message> slug: Web/XSLT/Element/message page-type: xslt-element --- {{XsltSidebar}} The `<xsl:message>` element outputs a message (to the JavaScript Console in NS) and optionally terminates execution of the stylesheet. It can be useful for debugging. ### Syntax ```xml <xsl:message terminate="yes" | "no" > TEMPLATE </xsl:message> ``` ### Required Attributes None. ### Optional Attributes - `terminate` - : Set to "`yes`", indicates that execution should be terminated. The default value is "`no`", in which case the message is output and execution continues. ### Type Instruction, appears within a template. ### Defined XSLT, section 13. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/value-of/index.md
--- title: <xsl:value-of> slug: Web/XSLT/Element/value-of page-type: xslt-element --- {{XsltSidebar}} The `<xsl:value-of>` element evaluates an XPath expression, converts it to a string, and writes that string to the result tree. ### Syntax ```xml <xsl:value-of select=EXPRESSION disable-output-escaping="yes" | "no" /> ``` ### Required Attributes - `select` - : Specifies the XPath expression to be evaluated and written to the output tree. ### Optional Attributes - `disable-output-escaping` (Netscape does not serialize the result of transformation - the "output" below - so this attribute is essentially irrelevant in context. To output html-entities, use numerical values instead, eg `&#160` for `&nbsp`) - : Specifies whether special characters are escaped when written to the output. The available values are "`yes`" or "`no`". If "`yes`" is set, for example, the character > is output as `>`, not as "`&gt`". ### Type Instruction, appears with a template. ### Defined XSLT, section 7.6.1. ### Gecko support Supported except as above.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/with-param/index.md
--- title: <xsl:with-param> slug: Web/XSLT/Element/with-param page-type: xslt-element --- {{XsltSidebar}} The `<xsl:with-param>` element sets the value of a parameter to be passed into a template. ### Syntax ```xml <xsl:with-param name=NAME select=EXPRESSION> TEMPLATE </xsl:with-param> ``` ### Required Attributes - `name` - : Gives this parameter a name. ### Optional Attributes - `select` - : Defines the value of the parameter through an XPath expression. If the element contains a template, this attribute is ignored. ### Type Subinstruction, always appears within an `<xsl:apply-templates>` or an `<xsl:call-template>` element. ### Defined XSLT 11.6 ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/decimal-format/index.md
--- title: <xsl:decimal-format> slug: Web/XSLT/Element/decimal-format page-type: xslt-element --- {{XsltSidebar}} The `<xsl:decimal-format>` element defines the characters and symbols that are to be used in converting numbers into strings using the `format-number( )` function. ### Syntax ```xml <xsl:decimal-format name=NAME decimal-separator=CHARACTER grouping-separator=CHARACTER infinity=STRING minus-sign=CHARACTER NaN=STRING percent=CHARACTER per-mille=CHARACTER zero-digit=CHARACTER digit=CHARACTER pattern-separator=CHARACTER /> ``` ### Required Attributes None. ### Optional Attributes - `name` - : Specifies a name for this format. - `decimal-separator` - : Specifies the decimal point character. The default is (`.`). - `grouping-separator` - : Specifies the thousands separator character. The default is (`,`). - `infinity` - : Specifies the string used to represent infinity. The default is the string "`Infinity`". - `minus-sign` - : Specifies the minus sign character. The default is the hyphen (`-`). - `NaN` - : Specifies the string used when the value is not a number. The default is the string "`NaN`". - `percent` - : Specifies the percentage sign character. The default is (`%`). - `per-mille` - : Specifies the per thousand character. The default is (`‰`). - `zero-digit` - : Specifies the digit zero character. The default is (`0`). - `digit` - : Specifies the character used in the format pattern to stand for a digit. The default is (`#`). - `pattern-separator` - : Specifies the character separating positive and negative subpatterns in a format pattern. The default is the semicolon (`;`). ### Type Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 12.3. ### Gecko support Supported as of 1.0 (Mozilla 1.0, Netscape 7.0).
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/otherwise/index.md
--- title: <xsl:otherwise> slug: Web/XSLT/Element/otherwise page-type: xslt-element --- {{XsltSidebar}} The `<xsl:otherwise>` element is used to define the action that should be taken when none of the `<xsl:when>` conditions apply. It is similar to the `else` or `default` case in other programming languages. ### Syntax ```xml <xsl:otherwise> TEMPLATE </xsl:otherwise> ``` ### Required Attributes None. ### Optional Attributes None. ### Type Subinstruction, must appear as the last child of an `<xsl:choose>` element, within a template. ### Defined XSLT, section 9.2 ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/fallback/index.md
--- title: <xsl:fallback> slug: Web/XSLT/Element/fallback page-type: xslt-element --- {{XsltSidebar}} The `<xsl:fallback>` element specifies what template to use if a given extension (or, eventually, newer version) element is not supported. ### Syntax ```xml <xsl:fallback> TEMPLATE </xsl:fallback> ``` ### Required Attributes None. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 15 ### Gecko support Not supported at this time.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/key/index.md
--- title: <xsl:key> slug: Web/XSLT/Element/key page-type: xslt-element --- {{XsltSidebar}} The `<xsl:key>` element declares a named key which can be used elsewhere in the stylesheet with the `key( )` function. ### Syntax ```xml <xsl:key name=NAME match=EXPRESSION use=EXPRESSION /> ``` ### Required Attributes - `name` - : Specifies a name for this key. Must be a QName. - `match` - : Defines the nodes for which this key is applicable. - `use` - : Specifies an XPath expression that will be used to determine the value of the key for each of the applicable nodes. ### Optional Attributes None. ### Type Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`. ### Defined XSLT, section 12.2. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/for-each/index.md
--- title: <xsl:for-each> slug: Web/XSLT/Element/for-each page-type: xslt-element --- {{XsltSidebar}} The `<xsl:for-each>` element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more `<xsl:sort>` elements appear as the children of this element, sorting occurs before processing. Otherwise, nodes are processed in document order. ### Syntax ```xml <xsl:for-each select=EXPRESSION> <xsl:sort> [optional] TEMPLATE </xsl:for-each> ``` ### Required Attributes - `select` - : Uses an XPath expression to select nodes to be processed. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 8. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/param/index.md
--- title: <xsl:param> slug: Web/XSLT/Element/param page-type: xslt-element --- {{XsltSidebar}} The `<xsl:param>` element establishes a parameter by name and, optionally, a default value for that parameter. When used as a top-level element, the parameter is global. When used inside an `<xsl:template>` element, the parameter is local to that template. In this case it must be the first child element of the template. ### Syntax ```xml <xsl:param name=NAME select=EXPRESSION> TEMPLATE </xsl:param> ``` ### Required Attributes - `name` - : Names the parameter. This must be a QName. ### Optional Attributes - `select` - : Uses an XPath expression to provide a default value if none is specified. ### Type Instruction, can appear as a top-level element or within a template. ### Defined XSLT, section 11. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/attribute/index.md
--- title: <xsl:attribute> slug: Web/XSLT/Element/attribute page-type: xslt-element --- {{XsltSidebar}} The `<xsl:attribute>` element creates an attribute in the output document, using any values that can be accessed from the stylesheet. The element must be defined before any other output document element inside the output document element for which it establishes attribute values. But it may be after or inside elements that won't be part of the output (like `<xsl:choose>` or `<xsl:apply-templates>` etc.). ### Syntax ```xml <xsl:attribute name=NAME namespace=URI> TEMPLATE </xsl:attribute> ``` ### Required Attributes - `name` - : Specifies the name of the attribute to be created in the output document. The name must be a valid QName. ### Optional Attributes - `namespace` - : Defines the namespace URI for this attribute in the output document. You cannot set the related namespace prefix with this element. ### Type Instruction, appears within a template or an `<xsl:attribute-set>` element. ### Defined XSLT, section 7.1.3. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/sort/index.md
--- title: <xsl:sort> slug: Web/XSLT/Element/sort page-type: xslt-element --- {{XsltSidebar}} The `<xsl:sort>` element defines a sort key for nodes selected by `<xsl:apply-templates>` or `<xsl:for-each>` and determines the order in which they are processed. ### Syntax ```xml <xsl:sort select=EXPRESSION order="ascending" | "descending" case-order="upper-first" | "lower-first" lang=XML:LANG-CODE data-type="text" | "number" /> ``` ### Required Attributes None. ### Optional Attributes - `select` - : Uses an XPath expression to specify the nodes to be sorted. - `order` - : Specifies whether the nodes should be processed in "`ascending`" or "`descending`" order. The default is "`ascending`". - `case-order` - : Indicates whether upper- or lowercase letters are to be ordered first. The allowable values are "`upper-first`" and "`lower-first`". - `lang` - : Specifies which language is to be used by the sort. - `data-type` - : Defines whether items are to be ordered alphabetically or numerically. The allowable values are "`text`" and "`number`" with "`text`" being the default. ### Type Subinstruction, always appears as a child of \<xsl:for-each>, where it must appear before the template proper or of \<xsl:apply-templates>. ### Defined XSLT, section10. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/copy/index.md
--- title: <xsl:copy> slug: Web/XSLT/Element/copy page-type: xslt-element --- {{XsltSidebar}} The `<xsl:copy>` element transfers a shallow copy (the node and any associated namespace node) of the current node to the output document. It does not copy any children or attributes of the current node. ### Syntax ```xml <xsl:copy use-attribute-sets=LIST-OF-NAMES> TEMPLATE </xsl:copy> ``` ### Required Attributes None. ### Optional Attributes - `use-attribute-sets` - : Lists attribute sets that should be applied to the output node, if it is an element. Names of the sets should be separated with whitespace characters. ### Type Instruction, appears within a template. ### Defined XSLT, section 7.5. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/choose/index.md
--- title: <xsl:choose> slug: Web/XSLT/Element/choose page-type: xslt-element --- {{XsltSidebar}} The `<xsl:choose>` element defines a choice among a number of alternatives. It behaves like a switch statement in procedural languages. ### Syntax ```xml <xsl:choose> <xsl:when test="[whatever to test1]"></xsl:when> <xsl:when test="[whatever to test2]"></xsl:when> <xsl:otherwise></xsl:otherwise> [optional] </xsl:choose> ``` ### Required Attributes None. ### Optional Attributes None. ### Type Instruction, appears with a template. It contains one or more `<xsl:when>` elements, and, optionally, a final `<xsl:otherwise>` element. ### Defined XSLT, section 9.2. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt/element
data/mdn-content/files/en-us/web/xslt/element/call-template/index.md
--- title: <xsl:call-template> slug: Web/XSLT/Element/call-template page-type: xslt-element --- {{XsltSidebar}} The `<xsl:call-template>` element invokes a named template. ### Syntax ```xml <xsl:call-template name=NAME> <xsl:with-param> [optional] </xsl:call-template> ``` ### Required Attribute - `name` - : Specifies the name of the template you wish to invoke. ### Optional Attributes None. ### Type Instruction, appears within a template. ### Defined XSLT, section 6. ### Gecko support Supported.
0
data/mdn-content/files/en-us/web/xslt
data/mdn-content/files/en-us/web/xslt/common_errors/index.md
--- title: Common XSLT Errors slug: Web/XSLT/Common_errors page-type: guide --- {{XsltSidebar}} ### MIME types Your server needs to send both the source and the stylesheet with a XML mime type, `text/xml` or `application/xml`. To find out the current type, load the file in Mozilla and look at the page info. Or use a download tool, those usually tell the mime type. In Firefox 6 and forward, you can also use the official XSLT mimetype: `application/xslt+xml`. ### Namespace The XSLT 1.0 namespace is [`http://www.w3.org/1999/XSL/Transform`](https://www.w3.org/1999/XSL/Transform). Older versions of IE used a different namespace. However these versions also used a draft version of XSLT which is incompatible with what eventually became the XSLT 1.0 specification. Firefox only supports the official XSLT 1.0 version. ### Missing features There are some features in the XSLT 1.0 specification which Firefox unfortunately does not yet support. Specifically: - The `namespace::` axis in XPath expressions. Support for this will hopefully be available in the future. - The `disable-output-escaping` attribute. This feature controls how serializing the constructed output document works. However Firefox never serializes the output document and so the attribute isn't really applicable. While we could try to add some heuristics to serialize and reparse just the part of the output document which has `disable-output-escaping` applied, heuristics often get things wrong and lead to surprising results, hence we've been reluctant to add this so far. Often times stylesheets contain code like `<xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>`, this is equivalent to putting `&#160;` in the stylesheet which will work great in all XSLT engines. We do realize that the lack of `disable-output-escaping` is a problem and we'd like to find a solution for it, however so far we haven't found any good solutions. - The `<xsl:namespace-alias>` element. If you'd like to help out with any of the above features, help would be greatly appreciated.
0
data/mdn-content/files/en-us/web/xslt
data/mdn-content/files/en-us/web/xslt/pi_parameters/index.md
--- title: PI Parameters slug: Web/XSLT/PI_Parameters page-type: guide --- {{XsltSidebar}} ### Overview XSLT supports the concept of passing parameters to a stylesheet when executing it. This has been possible for a while when using the {{domxref("XSLTProcessor")}} in JavaScript. However when using an `<?xml-stylesheet?>` processing instruction (PI) there used to be no way to provide parameters. To solve this two new PIs are implemented in [Firefox 2](/en-US/docs/Mozilla/Firefox/Releases/2) (see [Supported versions](#supported_versions) below for details), `<?xslt-param?>` and `<?xslt-param-namespace?>`. Both PIs can contain "pseudo attributes" the same way that the `xml-stylesheet` PI does. The following document passes the two parameters "color" and "size" to the stylesheet "style.xsl". ```xml <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> ``` Note that these PIs have no effect when transformation is done using the `XSLTProcessor` object in JavaScript. ### Processing instructions The attributes in the `xslt-param` and `xslt-param-namespace` PIs are parsed using the rules defined in [xml-stylesheet](https://www.w3.org/TR/xml-stylesheet/). Any unrecognized attributes must be ignored. Parsing of any attribute must not fail due to the presence of an unrecognized attribute as long as that attribute follows the syntax in `xml-stylesheet`. Both the `xslt-param` and the `xslt-param-namespace` PIs must appear in the prolog of the document, i.e. before the first element tag. All PIs in the prolog must be honored, both ones occurring before and ones occurring after any `xml-stylesheet` PIs. If there are multiple `xml-stylesheet` PIs the parameters apply to all stylesheets as a consequence of that all stylesheets are imported into a single stylesheet per the XSLT spec.reference? Note that multiple `xml-stylesheet` XSLT PIs are not supported in Firefox currently. #### xslt-param The `xslt-param` PI supports 4 attributes: - `name` - : The local-name part of the parameter name. No syntax checking is done on the attribute, however if it is not a valid [NCName](https://www.w3.org/TR/REC-xml-names/#NT-NCName) it will never match any parameter in the stylesheet. - `namespace` - : The namespace of the parameter name. No syntax checking is done on the attribute. - `value` - : Contains the string value for the parameter. The value of the attribute is used as value for the parameter. The datatype will always be _string_. - `select` - : An [XPath](/en-US/docs/Web/XPath) expression for the parameter. The value of the attribute is parsed as an XPath expression. The result of evaluating the expression is used as value for the parameter. If the `name` attribute is missing or empty the PI is ignored. If the `namespace` attribute is missing or empty the null namespace is used. It is not an error to specify a parameter name that does not exist in the stylesheet (or that is a variable in the stylesheet). The PI is ignored. If both `value` and `select` are present or if neither `value` nor `select` are present the PI is ignored. Note that `value="..."` is not strictly equal to `select="'...'"` since the value can contain both apostrophe and quote characters. ##### Examples Set the parameter 'color' to the string 'red': ```xml <?xslt-param name="color" value="red"?> ``` Set the parameter 'columns' to the number 2: ```xml <?xslt-param name="columns" select="2"?> ``` Set the parameter 'books' to a nodeset containing all `<book>` elements in the null namespace: ```xml <?xslt-param name="books" select="//book"?> ``` Set the parameter 'show-toc' to boolean `true`: ```xml <?xslt-param name="show-toc" select="true()"?> ``` ##### The select attribute context The following context is used to parse and evaluate the expression in the **select** attribute. - The context node is the node used as initial current node used when executing the stylesheet. - The context position is the position of the context node in the initial current node list used when executing the stylesheet. - The context size is the size of the initial current node list used when executing the stylesheet. - No variables are available. - The function library is the standard XPath function library. - The namespace declarations are determined by the `xslt-param-namespace` PIs, see below. If the **select** attribute fails to parse or execute, the PI is ignored (in particular, it does not fall back to the **value** attribute). #### xslt-param-namespace The `xslt-param-namespace` uses two attributes: - prefix - : The prefix that is mapped. - namespace - : The namespace the prefix maps to. An `xslt-param-namespace` PI affects the expression in the **select** attribute for all `xslt-param`s following the PI. This applies even if there are other nodes such as comments or other PIs between the `xslt-param-namespace` and `xslt-param` PIs. It is not an error for multiple PIs to use the same prefix, every new PI just changes what namespace the prefix maps to. If **prefix** is missing, empty, or equals an invalid NCName, the PI is ignored. If **namespace** is missing, the PI is ignored. If **namespace** is empty, the prefix mapping is removed. ##### Examples Set the parameter 'books' to a nodeset containing all `<book>` elements in the 'http\://www\.example.org/myNamespace' namespace: ```xml <?xslt-param-namespace prefix="my" namespace="http://www.example.org/myNamespace"?> <?xslt-param name="books" select="//my:book"?> ``` ### Supported versions Supported as of Firefox 2.0.0.1. The **value** attribute is supported in Firefox 2, but the **select** attribute crashes for some expressions in the 2.0 release. ### Possible future developments Should we allow any XSLT functions in the expression? `document()` seems useful, but it seems tricky to maintain the invariant that `generate-id()` should produce the same string for the same document. What about querying URL parameters in the XSLT stylesheet? E.g. Passing them to specified \<xsl:param>'s.
0
data/mdn-content/files/en-us/web/xslt
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/index.md
--- title: Transforming XML with XSLT slug: Web/XSLT/Transforming_XML_with_XSLT page-type: guide --- {{XsltSidebar}} ## An Overview [An Overview](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/An_Overview) The separation of content and presentation is a key design feature of [XML](/en-US/docs/Web/XML). The structure of an XML document is designed to reflect and clarify important relationships among the individual aspects of the content itself, unhindered by a need to provide any indication about how this data should eventually be presented. This intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network. Yet eventually much of the content stored in XML documents will need to be presented to human readers. Because a browser provides a familiar and highly flexible interface, it is an ideal mechanism for delivering such presentation versions of XML content. Built from the ground up utilizing a wide variety of XML technologies, Firefox incorporates within itself all of the mechanisms needed to process both original XML documents and the specialized stylesheets used to style and lay them out for HTML display, reducing server load with client-side processing. At present, Gecko (the layout engine behind Firefox) supports two forms of XML stylesheets. For basic control of appearance — fonts, colors, position, and so forth — Gecko uses [CSS](/en-US/docs/Web/CSS). Our focus here is on the second type of stylesheet that Gecko supports: the XSLT stylesheet. XSLT stands for eXtensible Stylesheet Language/Transform and the name is apt. XSLT allows a stylesheet author to transform a primary XML document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format (and in the case of Firefox, the focus is on converting it on the fly into HTML which can then be displayed by the browser). ## XSLT/XPath reference ### Elements [Elements](/en-US/docs/Web/XSLT/Element) - [xsl:apply-imports](/en-US/docs/Web/XSLT/Element/apply-imports) _(supported)_ - [xsl:apply-templates](/en-US/docs/Web/XSLT/Element/apply-templates) _(supported)_ - [xsl:attribute](/en-US/docs/Web/XSLT/Element/attribute) _(supported)_ - [xsl:attribute-set](/en-US/docs/Web/XSLT/Element/attribute-set) _(supported)_ - [xsl:call-template](/en-US/docs/Web/XSLT/Element/call-template) _(supported)_ - [xsl:choose](/en-US/docs/Web/XSLT/Element/choose) _(supported)_ - [xsl:comment](/en-US/docs/Web/XSLT/Element/comment) _(supported)_ - [xsl:copy](/en-US/docs/Web/XSLT/Element/copy) _(supported)_ - [xsl:copy-of](/en-US/docs/Web/XSLT/Element/copy-of) _(supported)_ - [xsl:decimal-format](/en-US/docs/Web/XSLT/Element/decimal-format) _(supported)_ - [xsl:element](/en-US/docs/Web/XSLT/Element/element) _(supported)_ - [xsl:fallback](/en-US/docs/Web/XSLT/Element/fallback) _(not supported)_ - [xsl:for-each](/en-US/docs/Web/XSLT/Element/for-each) _(supported)_ - [xsl:if](/en-US/docs/Web/XSLT/Element/if) _(supported)_ - [xsl:import](/en-US/docs/Web/XSLT/Element/import) _(mostly supported)_ - [xsl:include](/en-US/docs/Web/XSLT/Element/include) _(supported)_ - [xsl:key](/en-US/docs/Web/XSLT/Element/key) _(supported)_ - [xsl:message](/en-US/docs/Web/XSLT/Element/message) _(supported)_ - [xsl:namespace-alias](/en-US/docs/Web/XSLT/Element/namespace-alias) _(not supported)_ - [xsl:number](/en-US/docs/Web/XSLT/Element/number) _(partially supported)_ - [xsl:otherwise](/en-US/docs/Web/XSLT/Element/otherwise) _(supported)_ - [xsl:output](/en-US/docs/Web/XSLT/Element/output) _(partially supported)_ - [xsl:param](/en-US/docs/Web/XSLT/Element/param) _(supported)_ - [xsl:preserve-space](/en-US/docs/Web/XSLT/Element/preserve-space) _(supported)_ - [xsl:processing-instruction](/en-US/docs/Web/XSLT/Element/processing-instruction) - [xsl:sort](/en-US/docs/Web/XSLT/Element/sort) _(supported)_ - [xsl:strip-space](/en-US/docs/Web/XSLT/Element/strip-space) _(supported)_ - [xsl:stylesheet](/en-US/docs/Web/XSLT/Element/stylesheet) _(partially supported)_ - [xsl:template](/en-US/docs/Web/XSLT/Element/template) _(supported)_ - [xsl:text](/en-US/docs/Web/XSLT/Element/text) _(partially supported)_ - [xsl:transform](/en-US/docs/Web/XSLT/Element/transform) _(supported)_ - [xsl:value-of](/en-US/docs/Web/XSLT/Element/value-of) _(partially supported)_ - [xsl:variable](/en-US/docs/Web/XSLT/Element/variable) _(supported)_ - [xsl:when](/en-US/docs/Web/XSLT/Element/when) _(supported)_ - [xsl:with-param](/en-US/docs/Web/XSLT/Element/with-param) _(supported)_ ### Axes [Axes](/en-US/docs/Web/XPath/Axes) - [ancestor](/en-US/docs/Web/XPath/Axes#ancestor) - [ancestor-or-self](/en-US/docs/Web/XPath/Axes#ancestor-or-self) - [attribute](/en-US/docs/Web/XPath/Axes#attribute) - [child](/en-US/docs/Web/XPath/Axes#child) - [descendant](/en-US/docs/Web/XPath/Axes#descendant) - [descendant-or-self](/en-US/docs/Web/XPath/Axes#descendant-or-self) - [following](/en-US/docs/Web/XPath/Axes#following) - [following-sibling](/en-US/docs/Web/XPath/Axes#following-sibling) - [namespace](/en-US/docs/Web/XPath/Axes#namespace) _(not supported)_ - [parent](/en-US/docs/Web/XPath/Axes#parent) - [preceding](/en-US/docs/Web/XPath/Axes#preceding) - [preceding-sibling](/en-US/docs/Web/XPath/Axes#preceding-sibling) - [self](/en-US/docs/Web/XPath/Axes#self) ### Functions [Functions](/en-US/docs/Web/XPath/Functions) - [boolean()](/en-US/docs/Web/XPath/Functions/boolean) _(supported)_ - [ceiling()](/en-US/docs/Web/XPath/Functions/ceiling) _(supported)_ - [concat()](/en-US/docs/Web/XPath/Functions/concat) _(supported)_ - [contains()](/en-US/docs/Web/XPath/Functions/contains) _(supported)_ - [count()](/en-US/docs/Web/XPath/Functions/count) _(supported)_ - [current()](/en-US/docs/Web/XPath/Functions/current) _(supported)_ - [document()](/en-US/docs/Web/XPath/Functions/document) _(supported)_ - [element-available()](/en-US/docs/Web/XPath/Functions/element-available) _(supported)_ - [false()](/en-US/docs/Web/XPath/Functions/false) _(supported)_ - [floor()](/en-US/docs/Web/XPath/Functions/floor) _(supported)_ - [format-number()](/en-US/docs/Web/XPath/Functions/format-number) _(supported)_ - [function-available()](/en-US/docs/Web/XPath/Functions/function-available) _(supported)_ - [generate-id()](/en-US/docs/Web/XPath/Functions/generate-id) _(supported)_ - [id()](/en-US/docs/Web/XPath/Functions/id) _(partially supported)_ - [key()](/en-US/docs/Web/XPath/Functions/key) _(supported)_ - [lang()](/en-US/docs/Web/XPath/Functions/lang) _(supported)_ - [last()](/en-US/docs/Web/XPath/Functions/last) _(supported)_ - [local-name()](/en-US/docs/Web/XPath/Functions/local-name) _(supported)_ - [name()](/en-US/docs/Web/XPath/Functions/name) _(supported)_ - [namespace-uri()](/en-US/docs/Web/XPath/Functions/namespace-uri) _(supported)_ - [normalize-space()](/en-US/docs/Web/XPath/Functions/normalize-space) _(supported)_ - [not()](/en-US/docs/Web/XPath/Functions/not) _(supported)_ - [number()](/en-US/docs/Web/XPath/Functions/number) _(supported)_ - [position()](/en-US/docs/Web/XPath/Functions/position) _(supported)_ - [round()](/en-US/docs/Web/XPath/Functions/round) _(supported)_ - [starts-with()](/en-US/docs/Web/XPath/Functions/starts-with) _(supported)_ - [string()](/en-US/docs/Web/XPath/Functions/string) _(supported)_ - [string-length()](/en-US/docs/Web/XPath/Functions/string-length) _(supported)_ - [substring()](/en-US/docs/Web/XPath/Functions/substring) _(supported)_ - [substring-after()](/en-US/docs/Web/XPath/Functions/substring-after) _(supported)_ - [substring-before()](/en-US/docs/Web/XPath/Functions/substring-before) _(supported)_ - [sum()](/en-US/docs/Web/XPath/Functions/sum) _(supported)_ - [system-property()](/en-US/docs/Web/XPath/Functions/system-property) _(supported)_ - [translate()](/en-US/docs/Web/XPath/Functions/translate) _(supported)_ - [true()](/en-US/docs/Web/XPath/Functions/true) _(supported)_ - [unparsed-entity-url()](/en-US/docs/Web/XPath/Functions/unparsed-entity-url) _(not supported)_ ## For Further Reading [For Further Reading](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading) - [Books](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading#books) - [Digital](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading#digital) - [Websites](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading#websites) - [Articles](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading#articles) - [Tutorials/Examples](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading#tutorialsexamples) - [Other](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading#other) ## Original Document Information - Copyright Information: Copyright © 2001-2003 Netscape. All rights reserved. - Note: This reprinted article was originally part of the DevEdge site.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/index.md
--- title: The Netscape XSLT/XPath Reference slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference page-type: landing-page --- {{XsltSidebar}} The following is an alphabetized and annotated list of the elements, axes, and functions from the W3C's 1.0 Recommendation for XSLT, as well as from the appropriate sections of the XPath Recommendation. Development of the XSLT processor is ongoing, and this document will be updated as functionality is expanded. ### Elements - [xsl:apply-imports](/en-US/docs/Web/XSLT/Element/apply-imports) _(supported)_ - [xsl:apply-templates](/en-US/docs/Web/XSLT/Element/apply-templates) _(supported)_ - [xsl:attribute](/en-US/docs/Web/XSLT/Element/attribute) _(supported)_ - [xsl:attribute-set](/en-US/docs/Web/XSLT/Element/attribute-set) _(supported)_ - [xsl:call-template](/en-US/docs/Web/XSLT/Element/call-template) _(supported)_ - [xsl:choose](/en-US/docs/Web/XSLT/Element/choose) _(supported)_ - [xsl:comment](/en-US/docs/Web/XSLT/Element/comment) _(supported)_ - [xsl:copy](/en-US/docs/Web/XSLT/Element/copy) _(supported)_ - [xsl:copy-of](/en-US/docs/Web/XSLT/Element/copy-of) _(supported)_ - [xsl:decimal-format](/en-US/docs/Web/XSLT/Element/decimal-format) _(supported)_ - [xsl:element](/en-US/docs/Web/XSLT/Element) _(supported)_ - [xsl:fallback](/en-US/docs/Web/XSLT/Element/fallback) _(not supported)_ - [xsl:for-each](/en-US/docs/Web/XSLT/Element/for-each) _(supported)_ - [xsl:if](/en-US/docs/Web/XSLT/Element/if) _(supported)_ - [xsl:import](/en-US/docs/Web/XSLT/Element/import) _(mostly supported)_ - [xsl:include](/en-US/docs/Web/XSLT/Element/include) _(supported)_ - [xsl:key](/en-US/docs/Web/XSLT/Element/key) _(supported)_ - [xsl:message](/en-US/docs/Web/XSLT/Element/message) _(supported)_ - [xsl:namespace-alias](/en-US/docs/Web/XSLT/Element/namespace-alias) _(not supported)_ - [xsl:number](/en-US/docs/Web/XSLT/Element/number) _(partially supported)_ - [xsl:otherwise](/en-US/docs/Web/XSLT/Element/otherwise) _(supported)_ - [xsl:output](/en-US/docs/Web/XSLT/Element/output) _(partially supported)_ - [xsl:param](/en-US/docs/Web/XSLT/Element/param) _(supported)_ - [xsl:preserve-space](/en-US/docs/Web/XSLT/Element/preserve-space) _(supported)_ - [xsl:processing-instruction](/en-US/docs/Web/XSLT/Element/processing-instruction) - [xsl:sort](/en-US/docs/Web/XSLT/Element/sort) _(supported)_ - [xsl:strip-space](/en-US/docs/Web/XSLT/Element/strip-space) _(supported)_ - [xsl:stylesheet](/en-US/docs/Web/XSLT/Element/stylesheet) _(partially supported)_ - [xsl:template](/en-US/docs/Web/XSLT/Element/template) _(supported)_ - [xsl:text](/en-US/docs/Web/XSLT/Element/text) _(partially supported)_ - [xsl:transform](/en-US/docs/Web/XSLT/Element/transform) _(supported)_ - [xsl:value-of](/en-US/docs/Web/XSLT/Element/value-of) _(partially supported)_ - [xsl:variable](/en-US/docs/Web/XSLT/Element/variable) _(supported)_ - [xsl:when](/en-US/docs/Web/XSLT/Element/when) _(supported)_ - [xsl:with-param](/en-US/docs/Web/XSLT/Element/with-param) _(supported)_ ### Axes - [ancestor](/en-US/docs/Web/XPath/Axes#ancestor) - [ancestor-or-self](/en-US/docs/Web/XPath/Axes#ancestor-or-self) - [attribute](/en-US/docs/Web/XPath/Axes#attribute) - [child](/en-US/docs/Web/XPath/Axes#child) - [descendant](/en-US/docs/Web/XPath/Axes#descendant) - [descendant-or-self](/en-US/docs/Web/XPath/Axes#descendant-or-self) - [following](/en-US/docs/Web/XPath/Axes#following) - [following-sibling](/en-US/docs/Web/XPath/Axes#following-sibling) - [namespace](/en-US/docs/Web/XPath/Axes#namespace) _(not supported)_ - [parent](/en-US/docs/Web/XPath/Axes#parent) - [preceding](/en-US/docs/Web/XPath/Axes#preceding) - [preceding-sibling](/en-US/docs/Web/XPath/Axes#preceding-sibling) - [self](/en-US/docs/Web/XPath/Axes#self) ### Functions - [boolean()](/en-US/docs/Web/XPath/Functions/boolean) _(supported)_ - [ceiling()](/en-US/docs/Web/XPath/Functions/ceiling) _(supported)_ - [concat()](/en-US/docs/Web/XPath/Functions/concat) _(supported)_ - [contains()](/en-US/docs/Web/XPath/Functions/contains) _(supported)_ - [count()](/en-US/docs/Web/XPath/Functions/count) _(supported)_ - [current()](/en-US/docs/Web/XPath/Functions/current) _(supported)_ - [document()](/en-US/docs/Web/XPath/Functions/document) _(supported)_ - [element-available()](/en-US/docs/Web/XPath/Functions/element-available) _(supported)_ - [false()](/en-US/docs/Web/XPath/Functions/false) _(supported)_ - [floor()](/en-US/docs/Web/XPath/Functions/floor) _(supported)_ - [format-number()](/en-US/docs/Web/XPath/Functions/format-number) _(supported)_ - [function-available()](/en-US/docs/Web/XPath/Functions/function-available) _(supported)_ - [generate-id()](/en-US/docs/Web/XPath/Functions/generate-id) _(supported)_ - [id()](/en-US/docs/Web/XPath/Functions/id) _(partially supported)_ - [key()](/en-US/docs/Web/XPath/Functions/key) _(supported)_ - [lang()](/en-US/docs/Web/XPath/Functions/lang) _(supported)_ - [last()](/en-US/docs/Web/XPath/Functions/last) _(supported)_ - [local-name()](/en-US/docs/Web/XPath/Functions/local-name) _(supported)_ - [name()](/en-US/docs/Web/XPath/Functions/name) _(supported)_ - [namespace-uri()](/en-US/docs/Web/XPath/Functions/namespace-uri) _(supported)_ - [normalize-space()](/en-US/docs/Web/XPath/Functions/normalize-space) _(supported)_ - [not()](/en-US/docs/Web/XPath/Functions/not) _(supported)_ - [number()](/en-US/docs/Web/XPath/Functions/number) _(supported)_ - [position()](/en-US/docs/Web/XPath/Functions/position) _(supported)_ - [round()](/en-US/docs/Web/XPath/Functions/round) _(supported)_ - [starts-with()](/en-US/docs/Web/XPath/Functions/starts-with) _(supported)_ - [string()](/en-US/docs/Web/XPath/Functions/string) _(supported)_ - [string-length()](/en-US/docs/Web/XPath/Functions/string-length) _(supported)_ - [substring()](/en-US/docs/Web/XPath/Functions/substring) _(supported)_ - [substring-after()](/en-US/docs/Web/XPath/Functions/substring-after) _(supported)_ - [substring-before()](/en-US/docs/Web/XPath/Functions/substring-before) _(supported)_ - [sum()](/en-US/docs/Web/XPath/Functions/sum) _(supported)_ - [system-property()](/en-US/docs/Web/XPath/Functions/system-property) _(supported)_ - [translate()](/en-US/docs/Web/XPath/Functions/translate) _(supported)_ - [true()](/en-US/docs/Web/XPath/Functions/true) _(supported)_ - [unparsed-entity-url()](/en-US/docs/Web/XPath/Functions/unparsed-entity-url) _(not supported)_
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/ancestor/index.md
--- title: ancestor slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/ancestor page-type: xslt-axis --- {{XsltSidebar}} The ancestor axis indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/parent/index.md
--- title: parent slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/parent page-type: xslt-axis --- {{XsltSidebar}} The parent axis indicates the single node that is the parent of the context node. It can be abbreviated as two periods (`..`).
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/ancestor-or-self/index.md
--- title: ancestor-or-self slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/ancestor-or-self page-type: xslt-axis --- {{XsltSidebar}} The ancestor-or-self axis indicates the context node and all of its ancestors, including the root node.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/preceding/index.md
--- title: preceding slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/preceding page-type: xslt-axis --- {{XsltSidebar}} The preceding axis indicates all the nodes that precede the context node in the document except any ancestor, attribute, and namespace nodes.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/following-sibling/index.md
--- title: following-sibling slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/following-sibling page-type: xslt-axis --- {{XsltSidebar}} The following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/child/index.md
--- title: child slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/child page-type: xslt-axis --- {{XsltSidebar}} The child axis indicates the children of the context node. If an XPath expression does not specify an axis, the child axis is understood by default. Since only the root node or element nodes have children, any other use will select nothing.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/descendant-or-self/index.md
--- title: descendant-or-self slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/descendant-or-self page-type: xslt-axis --- {{XsltSidebar}} The descendant-or-self axis indicates the context node and all of its descendants. Attribute and namespace nodes are **not** included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/self/index.md
--- title: self slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/self page-type: xslt-axis --- {{XsltSidebar}} The self axis indicates the context node itself. It can be abbreviated as a single period (`.`).
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/descendant/index.md
--- title: descendant slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/descendant page-type: xslt-axis --- {{XsltSidebar}} The descendant axis indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are **not** included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/attribute/index.md
--- title: attribute slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/attribute page-type: xslt-axis --- {{XsltSidebar}} The attribute axis indicates the attributes of the context node. Only elements have attributes. This axis can be abbreviated with the at sign (`@`).
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/following/index.md
--- title: following slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/following page-type: xslt-axis --- {{XsltSidebar}} The following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/namespace/index.md
--- title: namespace slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/namespace page-type: xslt-axis --- {{XsltSidebar}} The namespace axis indicates all the nodes that are in scope for the context node. In this case, the context node must be an element node.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/the_netscape_xslt_xpath_reference/axes/preceding-sibling/index.md
--- title: preceding-sibling slug: Web/XSLT/Transforming_XML_with_XSLT/The_Netscape_XSLT_XPath_Reference/Axes/preceding-sibling page-type: xslt-axis --- {{XsltSidebar}} The preceding-sibling axis indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/for_further_reading/index.md
--- title: For further reading slug: Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading page-type: guide --- {{XsltSidebar}} [« Transforming XML with XSLT](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT) ## Print ### Books - **XSLT: Programmer's Reference, Second Edition** - **Author**: Michael H. Kay - **Length**: 992 pages - **Publisher**: Wrox; 2 edition (May 3, 2001) - **ISBN**: 0764543814 - Michael Kay is a member of the W3C XSL Working Group and the developer of his own open-source XSLT processor, Saxon. He is also the author of the only book on this subject to have reached a second edition. This is a very big book, well laid out, and exhaustive, if sometimes exhausting, in detail, covering every possible base in the XSLT story. <https://www.amazon.com/XSLT-Programmers-Reference-Programmer/dp/0764543814> - **XSLT** - **Author**: Doug Tidwell - **Length**: 473 pages - **Publisher**: O'Reilly Media; 1 edition (August 15, 2001) - **ISBN**: 0596000537 - Doug Tidwell is a senior developer at IBM and a prominent evangelist for XML technologies generally. He is the author of several articles and tutorials on various aspects of XML at IBM's extensive XML developer site. This book is somewhat less comprehensive than Michael Kay's, but it covers the basics well, and offers some intriguing examples. <https://www.amazon.com/Xslt-Doug-Tidwell/dp/0596000537> - **Learning XML, Second Edition** - **Author**: Erik T. Ray - **Length**: 432 pages - **Publisher**: O'Reilly Media; 2 edition (September 22, 2003) - **ISBN**: 0596004206 - As the title indicates, this is an overview of XML generally. Chapter 6 is devoted specifically to XSLT. <https://www.amazon.com/gp/product/0596004206> ## Digital ### Websites - **World Wide Web Consortium** - **The W3C homepage**: <https://www.w3.org> - **The main XSL page**: <https://www.w3.org/Style/XSL/> - **XSLT specifications overview**: <https://www.w3.org/TR/xslt/> - **Archive of public style (CSS and XSLT) discussions**: [https://lists.w3.org/Archives/Public/www-style/](https://lists.w3.org/Archives/Public/www-style/) - **XPath specifications overview**: <https://www.w3.org/TR/xpath/> - The World Wide Web Consortium is the body that publishes Recommendations for a number of web-based technologies, many of which become the de-facto standard. ### Articles - [Hands-on XSL](https://www.ibm.com/developerworks/library/x-hands-on-xsl/) by Don R. Day - [What is XSLT?](https://www.xml.com/pub/a/2000/08/holman/index.html) by G. Ken Holman ### Tutorials/Examples - [Jeni's XSLT Pages](https://www.jenitennison.com/xslt/) - [XMLPitstop.com](https://web.archive.org/web/20211209064736/https://www.xmlpitstop.com/default_datatype_SSC.html) - [XSL Tutorial](https://nwalsh.com/docs/tutorials/xsl/) ### Other - [Extensible Stylesheet Language (XSL)](https://xml.coverpages.org/xsl.html) - **XSL-List** - **Subscribe**: <https://www.mulberrytech.com/xsl/xsl-list/index.html> - **Archives**: <https://www.biglist.com/lists/xsl-list/archives/>
0
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt
data/mdn-content/files/en-us/web/xslt/transforming_xml_with_xslt/an_overview/index.md
--- title: An overview slug: Web/XSLT/Transforming_XML_with_XSLT/An_Overview page-type: guide --- {{XsltSidebar}} [« Transforming XML with XSLT](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT) The eXtensible Stylesheet Language/Transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of Netscape's capabilities that follows. - An XSLT stylesheet is an XML document. - : Unlike CSS, which has its own specialized syntax, an XSLT stylesheet is an XML document, which must conform to all XML rules, including well-formedness. So the model for transformation is that one XML document is used to transform another XML document. - An XSLT stylesheet is marked as such by the inclusion of a standard XSLT heading. - : The outermost element in an XSLT stylesheet must be the `<xsl:stylesheet>` element (an acceptable alternate is the `<xsl:transform>` element). This element will include at least one namespace declaration and the mandatory version attribute. Other namespaces and three optional attributes may also be included. - The mandatory namespace for XSLT is `"http://www.w3.org/1999/XSL/Transform"`. - : Namespaces are the subject of a fair amount of confusion in XML. Despite the fact that very often namespaces appear to be URIs, they do not, in fact, refer to a resource located at that address. Instead they are a way of specifying a unique identifier for a known set of elements. The string `"http://www.w3.org/1999/XSL/Transform"` is a constant that designates the elements so marked as belonging to the set of tags designated by the W3C in the 1999 XSLT Recommendation. Another string that is occasionally seen in stylesheets, `"http://www.w3.org/TR/WD-xsl"`, indicates compliance with an earlier working draft (hence the WD) of the W3C document. This latter namespace is not compatible with the one that the W3C eventually adopted and is not supported by Netscape. Because typing `"http://www.w3.org/1999/XSL/Transform"` repeatedly would be tedious and would render the markup difficult to read, there is a standard mechanism for assigning a shorthand name to the namespace in the stylesheet heading. Thus a full example of the opening stylesheet element might look like this. - `<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">` - : The xmlns pseudo-attribute maps the shorthand name xsl onto the full namespace for use throughout the document that follows. Thus the stylesheet element above is prefixed with `xsl:`. Although xsl is the conventionally used shorthand name (called the prefix), it is not mandatory and it is quite possible to choose a different one. The examples in this article all assume the use of the xsl prefix. - All XSLT transformations are performed on trees, not documents. - : The XSLT transformation engine, called the processor, does not work directly on documents. Before transformation can take place, the primary XML document(s) and the stylesheet document(s) must be run through a parser, which creates an abstract representation of the structure of the document in memory. This representation, called the tree, is what is actually manipulated by the processor. The tree is an abstract datatype, a conceptual model which can be implemented in various ways depending on the parser and the processor. :Netscape's uses a structure similar to the W3C DOM as its tree structure, but others are possible. The only requirements concern the disposition of objects in the tree, their properties, and their relationships. The tree consists of a hierarchical framework of nodes. It can be made up of seven different types of nodes: the single root node, element nodes, text nodes, attribute nodes, comment nodes, processing instruction nodes, and namespace nodes. At the top of the tree is the root node. The root node does not correspond to any individual part of the XML document: it represents the document as whole. Below the root node are its children, which can be elements, comments, processing instructions and so on. Some of those children may also have children. And this can continue for several levels. There are certain constraints on which type of nodes can occur where: for example, text nodes can have no children. The result of the processor's action is also a tree. Netscape uses this tree to render the contents in the browser window. - XSLT is a high-level declarative language. - : In essence, an XSLT stylesheet is a set of rules, called templates, which declare that any node that matches this specific pattern should be manipulated in this specific way and end up in this specific position in the result tree. The particulars of how this is to be accomplished are left up to the processor. Because the order of execution of the stylesheet cannot be guaranteed, XSLT does not support any functionality that produces side-effects. In this it is like Lisp or Scheme. - Locations on the tree are specified using XPath, another W3C Recommendation. - : Transformations depend on the processor's being able to pinpoint individual nodes on the tree. To facilitate this, the W3C decided to use a separate language, XPath, which also has uses outside the XSLT context. As its name implies, XPath defines a "path" the processor must take through the tree to arrive at the desired node. This path consists of XPath-specific expressions to be evaluated, expressions which may include a number of conditions to be matched, a way of associating nodes, and/or an indication of directionality within the tree. A fuller description of the parts of XPath most commonly used in XSLT follows in the reference section. - Potential conflicts in template matching are resolved by using a set of cascading precedence rules. - : In general, a more specific template rule takes precedence over a less specific one and, other things being equal, a template rule that appears later in the document takes precedence over one that appears earlier. - Stylesheets can be attached to an XML document via a processing instruction. - : The simplest way to indicate which XSLT stylesheet should be used to process a particular XML document is to include a processing instruction in the XML document itself. For example, if the stylesheet is called inventory.xsl and resides in the same directory as the XML document, the processing instruction in the XML document would look like this: - `<?xml-stylesheet type="text/xml" href="inventory.xsl"?>` - : This must be placed in the prolog section of the XML document. To learn more about XSLT and XPath, see the [For Further Reading](/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT/For_Further_Reading) section at the end of this article.
0
data/mdn-content/files/en-us/web
data/mdn-content/files/en-us/web/html/index.md
--- title: "HTML: HyperText Markup Language" slug: Web/HTML page-type: landing-page --- {{HTMLSidebar}} **HTML** (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation ([CSS](/en-US/docs/Web/CSS)) or functionality/behavior ([JavaScript](/en-US/docs/Web/JavaScript)). "Hypertext" refers to links that connect web pages to one another, either within a single website or between websites. Links are a fundamental aspect of the Web. By uploading content to the Internet and linking it to pages created by other people, you become an active participant in the World Wide Web. HTML uses "markup" to annotate text, images, and other content for display in a Web browser. HTML markup includes special "elements" such as {{HTMLElement("head")}}, {{HTMLElement("title")}}, {{HTMLElement("body")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("p")}}, {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("img")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("datalist")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("nav")}}, {{HTMLElement("search")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("video")}}, {{HTMLElement("ul")}}, {{HTMLElement("ol")}}, {{HTMLElement("li")}} and many others. An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "`<`" and "`>`". The name of an element inside a tag is case-insensitive. That is, it can be written in uppercase, lowercase, or a mixture. For example, the `<title>` tag can be written as `<Title>`, `<TITLE>`, or in any other way. However, the convention and recommended practice is to write tags in lowercase. The articles below can help you learn more about HTML. ## Key resources - HTML Introduction - : If you're new to web development, be sure to read our [HTML Basics](/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics) article to learn what HTML is and how to use it. - HTML Tutorials - : For articles about how to use HTML, as well as tutorials and complete examples, check out our [HTML Learning Area](/en-US/docs/Learn/HTML). - HTML Reference - : In our extensive [HTML reference](/en-US/docs/Web/HTML/Reference) section, you'll find the details about every element and attribute in HTML. > **Callout:** > > #### Looking to become a front-end web developer? > > We have put together a course that includes all the essential information you need to > work towards your goal. > > [**Get started**](/en-US/docs/Learn/Front-end_web_developer) ## Beginner's tutorials Our [HTML Learning Area](/en-US/docs/Learn/HTML) features multiple modules that teach HTML from the ground up — no previous knowledge required. - [Introduction to HTML](/en-US/docs/Learn/HTML/Introduction_to_HTML) - : This module sets the stage, getting you used to important concepts and syntax such as looking at applying HTML to text, how to create hyperlinks, and how to use HTML to structure a web page. - [Multimedia and embedding](/en-US/docs/Learn/HTML/Multimedia_and_embedding) - : This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages. - [HTML tables](/en-US/docs/Learn/HTML/Tables) - : Representing tabular data on a webpage in an understandable, accessible way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries. - [HTML forms](/en-US/docs/Learn/Forms) - : Forms are a very important part of the Web — these provide much of the functionality you need for interacting with websites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side/front-end parts of forms. - [Use HTML to solve common problems](/en-US/docs/Learn/HTML/Howto) - : Provides links to sections of content explaining how to use HTML to solve very common problems when creating a web page: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc. ## Advanced topics - [CORS enabled image](/en-US/docs/Web/HTML/CORS_enabled_image) - : The [`crossorigin`](/en-US/docs/Web/HTML/Element/img#crossorigin) attribute, in combination with an appropriate {{glossary("CORS")}} header, allows images defined by the {{HTMLElement("img")}} element to be loaded from foreign origins and used in a {{HTMLElement("canvas")}} element as if they were being loaded from the current origin. - [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) - : Some HTML elements that provide support for [CORS](/en-US/docs/Web/HTTP/CORS), such as {{HTMLElement("img")}} or {{HTMLElement("video")}}, have a `crossorigin` attribute (`crossOrigin` property), which lets you configure the CORS requests for the element's fetched data. - [Preloading content with rel="preload"](/en-US/docs/Web/HTML/Attributes/rel/preload) - : The `preload` value of the {{htmlelement("link")}} element's [`rel`](/en-US/docs/Web/HTML/Element/link#rel) attribute allows you to write declarative fetch requests in your HTML {{htmlelement("head")}}, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how `preload` works. ## Reference - [HTML reference](/en-US/docs/Web/HTML/Reference) - : HTML consists of **elements**, each of which may be modified by some number of **attributes**. HTML documents are connected to each other with **links**. - [HTML element reference](/en-US/docs/Web/HTML/Element) - : Browse a list of all {{glossary("HTML")}} {{glossary("Element", "elements")}}. - [HTML attribute reference](/en-US/docs/Web/HTML/Attributes) - : Elements in HTML have **attributes**. These are additional values that configure the elements or adjust their behavior in various ways. - [Global attributes](/en-US/docs/Web/HTML/Global_attributes) - : Global attributes may be specified on all [HTML elements](/en-US/docs/Web/HTML/Element), _even those not specified in the standard_. This means that any non-standard elements must still permit these attributes, even though those elements make the document HTML5-noncompliant. - [Inline-level elements](/en-US/docs/Glossary/Inline-level_content) and [block-level elements](/en-US/docs/Glossary/Block-level_content) - : HTML elements are usually "inline-level" or "block-level" elements. An inline-level element occupies only the space bounded by the tags that define it. A block-level element occupies the entire space of its parent element (container), thereby creating a "block box". - [Guide to media types and formats on the web](/en-US/docs/Web/Media/Formats) - : The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements allow you to play audio and video media natively within your content without the need for external software support. - [HTML content categories](/en-US/docs/Web/HTML/Content_categories) - : HTML is comprised of several kinds of content, each of which is allowed to be used in certain contexts and is disallowed in others. Similarly, each context has a set of other content categories it can contain and elements that can or can't be used in them. This is a guide to these categories. - [Quirks mode and standards mode](/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode) - : Historical information on quirks mode and standards mode. ## Related topics - [Applying color to HTML elements using CSS](/en-US/docs/Web/CSS/CSS_colors/Applying_color) - : This article covers most of the ways you use CSS to add color to HTML content, listing what parts of HTML documents can be colored and what CSS properties to use when doing so. Includes examples, links to palette-building tools, and more.
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/quirks_mode_and_standards_mode/index.md
--- title: Quirks Mode slug: Web/HTML/Quirks_Mode_and_Standards_Mode page-type: guide --- {{HTMLSidebar}} In the old days of the web, pages were typically written in two versions: One for Netscape Navigator, and one for Microsoft Internet Explorer. When the web standards were made at W3C, browsers could not just start using them, as doing so would break most existing sites on the web. Browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites. There are now three modes used by the layout engines in web browsers: quirks mode, limited-quirks mode, and no-quirks mode. In **quirks mode**, layout emulates behavior in Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards. In **no-quirks mode**, the behavior is (hopefully) the desired behavior described by the modern HTML and CSS specifications. In **limited-quirks mode**, there are only a very small number of quirks implemented. The limited-quirks and no-quirks modes used to be called "almost-standards" mode and "full standards" mode, respectively. These names have been changed as the behavior is now standardized. ## How do browsers determine which mode to use? For [HTML](/en-US/docs/Web/HTML) documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. To ensure that your page uses full standards mode, make sure that your page has a DOCTYPE like in this example: ```html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Hello World!</title> </head> <body></body> </html> ``` The DOCTYPE shown in the example, `<!DOCTYPE html>`, is the simplest possible, and the one recommended by current HTML standards. Earlier versions of the HTML standard recommended other variants, but all existing browsers today will use full standards mode for this DOCTYPE, even the dated Internet Explorer 6. There are no valid reasons to use a more complicated DOCTYPE. If you do use another DOCTYPE, you may risk choosing one which triggers almost standards mode or quirks mode. Make sure you put the DOCTYPE right at the beginning of your HTML document. Anything before the DOCTYPE, like a comment or an XML declaration will trigger quirks mode in Internet Explorer 9 and older. The only purpose of `<!DOCTYPE html>` is to activate no-quirks mode. Older versions of HTML standard DOCTYPEs provided additional meaning, but no browser ever used the DOCTYPE for anything other than switching between render modes. See also a detailed description of [when different browsers choose various modes](https://hsivonen.fi/doctype/). ### XHTML If you serve your page as [XHTML](/en-US/docs/Glossary/XHTML) using the `application/xhtml+xml` MIME type in the `Content-Type` HTTP header, you do not need a DOCTYPE to enable standards mode, as such documents always use 'full standards mode'. Note however that serving your pages as `application/xhtml+xml` will cause Internet Explorer 8 to show a download dialog box for an unknown format instead of displaying your page, as the first version of Internet Explorer with support for XHTML is Internet Explorer 9. If you serve XHTML-like content using the `text/html` MIME type, browsers will read it as HTML, and you will need the DOCTYPE to use standards mode. ## How do I see which mode is used? If the page is rendered in quirks or limited-quirks mode, Firefox will log a warning to the console tab in the developer tools. If this warning is not shown, Firefox is using no-quirks mode. The value of `document.compatMode` in JavaScript will show whether or not the document is in quirks mode. If its value is `"BackCompat"`, the document is in quirks mode. If it isn't, it will have value `"CSS1Compat"`.
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/microformats/index.md
--- title: Microformats slug: Web/HTML/microformats page-type: guide --- {{HTMLSidebar}} [_Microformats_](https://microformats.org/) are standards used to embed semantics and structured data in HTML, and provide an API to be used by social web applications, search engines, aggregators, and other tools. These minimal patterns of HTML are used for marking up entities that range from fundamental to domain-specific information, such as people, organizations, events, and locations. - To create a microformats object, h-\* class names are used in the class attribute. - To add a property to an object, the p-\*, u-\*, dt-\*, e-\* class names are used on one of the object's descendants. Microformats use supporting vocabularies to describe objects and name-value pairs to assign values to their properties. The properties are carried in class attributes that can be added to any HTML element, while the data values re-use HTML element content and semantic attributes. Microformats2 (sometimes referred to as mf2) is an update to microformats that provides a simpler way of annotating HTML structured syntax and vocabularies than previous approaches of using RDFa and microdata. These previous approaches require learning new attributes. There are [open source parsing libraries for most languages](https://microformats.org/wiki/microformats2#Parsers) for microformats2. ## How Microformats Work An author of a webpage can add microformats to their HTML. For example if they wanted to identify themselves they could use an [h-card](https://microformats.org/wiki/h-card) such as: ### HTML Example ```html <a class="h-card" href="https://alice.example.com">Alice Blogger</a> ``` When a parser encounters this data, it will know that this page contains a "card" which describes a person or organization named `Alice Blogger` with a URL of `https://alice.example.com/`. The parser makes this data available via APIs that can be used for different applications. For example, an application could scan a page for a h-card to use as profile information for someone who has signed up to a service. As in this example, some markup patterns require only a single microformat root class name, which parsers use to find a few generic properties such as `name`, `url`, `photo`. ## Microformats Use Cases Microformats have numerous use cases. First, the [Webmention standard](https://www.w3.org/TR/webmention/) uses microformats to provide a way in which messages and comments can be sent from one site to another. The Webmention specification defines specific attributes that sites may publish and consume to create a rich, interoperable way of publishing messages and comments. Microformats can also be used with Webmentions to enable sending social reactions such as likes, reposts, and bookmarks from one site to another. Microformats also enable easy syndication across sites. An aggregator could parse a page with published microformats to look for information such as a post title, a post body, and the author of a post. This aggregator could then use the semantic information gathered to render a result on their site. For instance, news aggregators and community posting boards could facilitate submissions and use microformats to exact relevant content from a page. Further, a website could use microformats to send crafted requests to third-parties to publish content, such as social networks. All major search engines support reading and interpreting microformats. Search engines benefit greatly from direct access to this structured data because it allows them to understand the information on web pages. With this information, search engines can provide more relevant results to users. Some search engines may render special snippets such as star ratings on a search result page based on the data provided in microformats. In addition to being machine-readable, microformats are designed to be easily read by humans. This approach makes it easy for people to understand and maintain microformats data. ## Microformats Prefixes All microformats consist of a root, and a collection of properties. Properties are all optional and potentially multivalued - applications needing a singular value may use the first instance of a property. Hierarchical data is represented with nested microformats, typically as property values themselves. All microformats class names use prefixes. Prefixes are **syntax independent of vocabularies**, which are developed separately. - **"h-\*" for root class names**, e.g. "h-card", "h-entry", "h-feed", and many more. These top-level root classes usually indicate a type and corresponding expected vocabulary of properties. For example: - [h-card](https://microformats.org/wiki/h-card) describes a person or organization - [h-entry](https://microformats.org/wiki/h-entry) describes episodic or date stamped online content like a blog post - [h-feed](https://microformats.org/wiki/h-feed) describes a stream or feed of posts - You can find many more [vocabularies on the microformats2 wiki.](https://microformats.org/wiki/microformats2#v2_vocabularies) - **"p-\*" for plain (text) properties**, e.g. "p-name", "p-summary" - Generic plain text parsing, element text in general. On certain HTML elements, use special attributes first, e.g. img/alt, abbr/title. - **"u-\*" for URL properties**, e.g. "u-url", "u-photo", "u-logo" - Special parsing: element attributes a/href, img/src, object/data etc. attributes over element contents. - **"dt-\*" for datetime properties**, e.g. "dt-start", "dt-end", "dt-bday" - Special parsing: time element datetime attribute, [value-class-pattern](https://microformats.org/wiki/value-class-pattern) and separate date time value parsing for readability. - **"e-\*" for element tree properties** where the entire contained element hierarchy is the value, e.g. "e-content". The "e-" prefix can also be mnemonically remembered as "element tree", "embedded markup", or "encapsulated markup". ## Some microformats examples ### h-card The [h-card](https://microformats.org/wiki/h-card) microformat represents a person or organization. The value of each property is defined in HTML using the class property any element can carry #### Example h-card ```html <p class="h-card"> <img class="u-photo" src="https://example.org/photo.png" alt="" /> <a class="p-name u-url" href="https://example.org">Joe Bloggs</a> <a class="u-email" href="mailto:[email protected]">[email protected]</a>, <span class="p-street-address">17 Austerstræti</span> <span class="p-locality">Reykjavík</span> <span class="p-country-name">Iceland</span> </p> ``` | Property | Description | | ---------------------- | -------------------------------------------------------------- | | **`p-name`** | The full/formatted name of the person or organization. | | **`u-email`** | email address | | **`u-photo`** | a photo of the person or organization | | **`u-url`** | home page or other URL representing the person or organization | | **`u-uid`** | universally unique identifier, preferably canonical URL | | **`p-street-address`** | street number + name | | **`p-locality`** | city/town/village | | **`p-country-name`** | country name | #### Nested h-card example ```html <div class="h-card"> <a class="p-name u-url" href="https://blog.lizardwrangler.com/"> Mitchell Baker </a> (<a class="p-org h-card" href="https://mozilla.org/">Mozilla Foundation</a>) </div> ``` Parsed JSON: ```json { "items": [ { "type": ["h-card"], "properties": { "name": ["Mitchell Baker"], "url": ["https://blog.lizardwrangler.com/"], "org": [ { "value": "Mozilla Foundation", "type": ["h-card"], "properties": { "name": ["Mozilla Foundation"], "url": ["https://mozilla.org/"] } } ] } } ] } ``` In this example, a h-card is specified for both a person and the organization they represent. The person's affiliation with the linked organization is specified using the p-org property. Note: the nested h-card has implied 'name' and 'url' properties, just like any other root-class-name-only h-card on an `<a href>` would. ### h-entry The [h-entry](https://microformats.org/wiki/h-entry) microformat represents episodic or datestamped content on the web. h-entry is often used with content intended to be syndicated, e.g. blog posts and short notes. Example h-entry as a blog post: ```html <article class="h-entry"> <h1 class="p-name">Microformats are amazing</h1> <p> Published by <a class="p-author h-card" href="https://example.com">W. Developer</a> on <time class="dt-published" datetime="2013-06-13 12:00:00"> 13<sup>th</sup> June 2013 </time> </p> <p class="p-summary">In which I extoll the virtues of using microformats.</p> <div class="e-content"> <p>Blah blah blah</p> </div> </article> ``` #### Properties | Property | Description | | ------------------ | ----------------------------------------------- | | **`p-name`** | entry name/title | | **`p-author`** | who wrote the entry, optionally embedded h-card | | **`dt-published`** | when the entry was published | | **`p-summary`** | short entry summary | | **`e-content`** | full content of the entry | #### Parsed reply h-entry example ```html <div class="h-entry"> <p> <span class="p-author h-card"> <a href="https://quickthoughts.jgregorymcverry.com/profile/jgmac1106"> <img class="u-photo" alt="Greg McVerry" src="https://quickthoughts.jgregorymcverry.com/file/2d6c9cfed7ac8e849f492b5bc7e6a630/thumb.jpg" /> </a> <a class="p-name u-url" href="https://quickthoughts.jgregorymcverry.com/profile/jgmac1106"> Greg McVerry </a> </span> Replied to <a class="u-in-reply-to" href="https://developer.mozilla.org/en-US/docs/Web/HTML/microformats"> a post on <strong>developer.mozilla.org</strong> </a> : </p> <p class="p-name e-content"> Hey thanks for making this microformats resource </p> <p> <a href="https://quickthoughts.jgregorymcverry.com/profile/jgmac1106"> Greg McVerry </a> published this <a class="u-url url" href="https://quickthoughts.jgregorymcverry.com/2019/05/31/hey-thanks-for-making-this-microformats-resource"> <time class="dt-published" datetime="2019-05-31T14:19:09+0000"> 31 May 2019 </time> </a> </p> </div> ``` ```json { "items": [ { "type": ["h-entry"], "properties": { "in-reply-to": [ "https://developer.mozilla.org/en-US/docs/Web/HTML/microformats" ], "name": ["Hey thanks for making this microformats resource"], "url": [ "https://quickthoughts.jgregorymcverry.com/2019/05/31/hey-thanks-for-making-this-microformats-resource" ], "published": ["2019-05-31T14:19:09+0000"], "content": [ { "html": "Hey thanks for making this microformats resource", "value": "Hey thanks for making this microformats resource", "lang": "en" } ], "author": [ { "type": ["h-card"], "properties": { "name": ["Greg McVerry"], "photo": [ "https://quickthoughts.jgregorymcverry.com/file/2d6c9cfed7ac8e849f492b5bc7e6a630/thumb.jpg" ], "url": [ "https://quickthoughts.jgregorymcverry.com/profile/jgmac1106" ] }, "lang": "en", "value": "Greg McVerry" } ] }, "lang": "en" } ] } ``` ### h-feed The [h-feed](https://microformats.org/wiki/h-feed) is a stream or feed of [h-entry](https://microformats.org/wiki/h-entry) posts, like complete posts on a home page or archive pages, or summaries or other brief lists of posts. #### Example h-feed ```html <div class="h-feed"> <h1 class="p-name">Microformats Blogs</h1> <article class="h-entry"> <h2 class="p-name">Microformats are amazing</h2> <p> Published by <a class="p-author h-card" href="https://example.com">W. Developer</a> on <time class="dt-published" datetime="2013-06-13 12:00:00"> 13<sup>th</sup> June 2013 </time> </p> <p class="p-summary"> In which I extoll the virtues of using microformats. </p> <div class="e-content"><p>Blah blah blah</p></div> </article> </div> ``` #### Properties | Property | Description | | -------------- | ---------------------------------------------- | | **`p-name`** | name of the feed | | **`p-author`** | author of the feed, optionally embed an h-card | #### Children <table class="standard-table"> <tbody> <tr> <td><strong>Nested h-entry</strong></td> <td></td> </tr> <tr> <td>objects representing the items of the feed</td> <td></td> </tr> </tbody> </table> ### h-event The `h-event` is for events on the web. h-event is often used with both event listings and individual event pages. ```html <div class="h-event"> <h1 class="p-name">Microformats Meetup</h1> <p> From <time class="dt-start" datetime="2013-06-30 12:00"> 30<sup>th</sup> June 2013, 12:00 </time> to <time class="dt-end" datetime="2013-06-30 18:00">18:00</time> at <span class="p-location">Some bar in SF</span> </p> <p class="p-summary"> Get together and discuss all things microformats-related. </p> </div> ``` #### Properties | Property | Description | | ---------------- | ------------------------------------------------------- | | **`p-name`** | event name (or title) | | **`p-summary`** | short summary of the event | | **`dt-start`** | datetime the event starts | | **`dt-end`** | datetime the event ends | | **`p-location`** | where the event takes place, optionally embedded h-card | #### Parsed h-event Example ```html <div class="h-event"> <h2 class="p-name">IndieWeb Summit</h2> <time class="dt-start" datetime="2019-06-29T09:00:00-07:00"> June 29, 2019 at 9:00am (-0700) </time> <br />through <time class="dt-end" datetime="2019-06-30T18:00:00-07:00"> June 30, 2019 at 6:00pm (-0700) </time> <br /> <div class="p-location h-card"> <div> <span class="p-name">Mozilla</span> </div> <div> <span class="p-street-address">1120 NW Couch St</span>, <span class="p-locality">Portland</span>, <span class="p-region">Oregon</span>, <span class="p-country">US</span> </div> <data class="p-latitude" value="45.52345"></data> <data class="p-longitude" value="-122.682677"></data> </div> <div class="e-content">Come join us</div> <div> <span class="p-author h-card"> <a class="u-url p-name" href="https://aaronparecki.com">Aaron Parecki</a> </span> Published this <a href="https://aaronparecki.com/2019/06/29/1/" class="u-url">event </a>on <time class="dt published" datetime="2019-05-25T18:00:00-07:00"> May 5th, 2019 </time> </div> </div> ``` ```json { "items": [ { "type": ["h-event"], "properties": { "name": ["IndieWeb Summit"], "url": ["https://aaronparecki.com/2019/06/29/1/"], "author": [ { "type": ["h-card"], "properties": { "name": ["Aaron Parecki"], "url": ["https://aaronparecki.com"] }, "lang": "en", "value": "Aaron Parecki" } ], "start": ["2019-06-29T09:00:00-07:00"], "end": ["2019-06-30T18:00:00-07:00"], "published": ["2019-05-25T18:00:00-07:00"], "content": [ { "html": "Come join us", "value": "Come join us", "lang": "en" } ], "location": [ { "type": ["h-card"], "properties": { "name": ["Mozilla"], "p-street-address": ["1120 NW Couch St"], "locality": ["Portland"], "region": ["Oregon"], "country": ["US"], "latitude": ["45.52345"], "longitude": ["-122.682677"] }, "lang": "en", "value": "Mozilla" } ] }, "lang": "en" } ] } ``` ## Microformats rel property examples There are some microformats that are applied to a page by using a special `rel=` property. These microformats describe a relation between a current document and a linked document. For a full list of these, see the [rel property](https://microformats.org/wiki/rel-values) on the microformats wiki. ### rel=author This attribute states that the linked document represents the author of the current page. ```html <a rel="author" href="https://jamesg.blog">James Gallagher</a> ``` ### rel=license This attribute states that the linked document contains the license under which the current page is published. ```html <a rel="license" href="https://mit-license.org/">MIT License</a> ``` ### rel=nofollow This attribute states that the linked document should not be given any weight by search engine ranking algorithms that may derive from the current page. This is useful to prevent link graph algorithms from weighing a page higher than it otherwise would after seeing a link to a document. ```html <a rel="nofollow" href="https://jamesg.blog">James Gallagher</a> ``` ## Browser compatibility Supported in all browsers' support for the class attribute and its DOM API. ## See also - [class attribute](/en-US/docs/Web/HTML/Global_attributes/class) - [Microformat](https://en.wikipedia.org/wiki/Microformat) on Wikipedia - [Microformats official website](https://microformats.org/) - [Search engines support](https://microformats.org/wiki/search_engines) on Microformats official website - [Microformats on IndieWebCamp](https://indieweb.org/microformats)
0
data/mdn-content/files/en-us/web/html
data/mdn-content/files/en-us/web/html/element/index.md
--- title: HTML elements reference slug: Web/HTML/Element page-type: landing-page --- {{HTMLSidebar("HTML_Elements")}} This page lists all the {{Glossary("HTML")}} {{Glossary("Element","elements")}}, which are created using {{Glossary("Tag", "tags")}}. They are grouped by function to help you find what you have in mind easily. An alphabetical list of all elements is provided in the sidebar on every element's page as well as this one. > **Note:** For more information about the basics of HTML elements and attributes, see [the section on elements in the Introduction to HTML article](/en-US/docs/Learn/HTML/Introduction_to_HTML#elements_%e2%80%94_the_basic_building_blocks). ## Main root | Element | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("html")}} | 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. | ## Document metadata Metadata contains information about the page. This includes information about styles, scripts and data to help software ({{Glossary("search engine", "search engines")}}, {{Glossary("Browser","browsers")}}, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or linked to another file that has the information. | Element | Description | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("base")}} | Specifies the base URL to use for all relative URLs in a document. There can be only one such element in a document. | | {{HTMLElement("head")}} | Contains machine-readable information (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). | | {{HTMLElement("link")}} | Specifies relationships between the current document and an external resource. This element is most commonly used to link to CSS 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. | | {{HTMLElement("meta")}} | Represents {{Glossary("Metadata","metadata")}} that cannot be represented by other HTML meta-related elements, like {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} and {{HTMLElement("title")}}. | | {{HTMLElement("style")}} | Contains style information for a document or part of a document. It contains CSS, which is applied to the contents of the document containing this element. | | {{HTMLElement("title")}} | Defines the document's title that is shown in a {{glossary("Browser", "browser")}}'s title bar or a page's tab. It only contains text; tags within the element are ignored. | ## Sectioning root | Element | Description | | ----------------------- | --------------------------------------------------------------------------------------------- | | {{HTMLElement("body")}} | represents the content of an HTML document. There can be only one such element in a document. | ## Content sectioning Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify sections of content. | Element | Description | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("address")}} | Indicates that the enclosed HTML provides contact information for a person or people, or for an organization. | | {{HTMLElement("article")}} | 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, a blog entry, a product card, a user-submitted comment, an interactive widget or gadget, or any other independent item of content. | | {{HTMLElement("aside")}} | Represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes. | | {{HTMLElement("footer")}} | Represents a footer for its nearest ancestor [sectioning content](/en-US/docs/Web/HTML/Content_categories#sectioning_content) or [sectioning root](/en-US/docs/Web/HTML/Element/Heading_Elements) element. A `<footer>` typically contains information about the author of the section, copyright data, or links to related documents. | | {{HTMLElement("header")}} | 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. | | [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements), [`<h2>`](/en-US/docs/Web/HTML/Element/Heading_Elements), [`<h3>`](/en-US/docs/Web/HTML/Element/Heading_Elements), [`<h4>`](/en-US/docs/Web/HTML/Element/Heading_Elements), [`<h5>`](/en-US/docs/Web/HTML/Element/Heading_Elements), [`<h6>`](/en-US/docs/Web/HTML/Element/Heading_Elements) | Represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. | | {{HTMLElement("hgroup")}} | Represents a heading grouped with any secondary content, such as subheadings, an alternative title, or a tagline. | | {{HTMLElement("main")}} | Represents the dominant content of the body of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. | | {{HTMLElement("nav")}} | Represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes. | | {{HTMLElement("section")}} | 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. | | {{HTMLElement("search")}} | Represents a part that contains a set of form controls or other content related to performing a search or filtering operation. | ## Text content Use HTML text content elements to organize blocks or sections of content placed between the opening {{HTMLElement("body")}} and closing `</body>` tags. Important for {{Glossary("accessibility")}} and {{Glossary("SEO")}}, these elements identify the purpose or structure of that content. | Element | Description | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("blockquote")}} | Indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation. A URL for the source of the quotation may be given using the `cite` attribute, while a text representation of the source can be given using the {{HTMLElement("cite")}} element. | | {{HTMLElement("dd")}} | Provides the description, definition, or value for the preceding term ({{HTMLElement("dt")}}) in a description list ({{HTMLElement("dl")}}). | | {{HTMLElement("div")}} | The generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g., styling is directly applied to it, or some kind of layout model like {{glossary("Flexbox", "flexbox")}} is applied to its parent element). | | {{HTMLElement("dl")}} | 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). | | {{HTMLElement("dt")}} | Specifies a term in a description or definition list, and as such must be used inside a {{HTMLElement("dl")}} element. It is usually followed by a {{HTMLElement("dd")}} element; however, multiple `<dt>` elements in a row indicate several terms that are all defined by the immediate next {{HTMLElement("dd")}} element. | | {{HTMLElement("figcaption")}} | Represents a caption or legend describing the rest of the contents of its parent {{HTMLElement("figure")}} element. | | {{HTMLElement("figure")}} | 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. | | {{HTMLElement("hr")}} | 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. | | {{HTMLElement("li")}} | Represents an item in a list. It must be contained in a parent element: an ordered list ({{HTMLElement("ol")}}), an unordered list ({{HTMLElement("ul")}}), or a menu ({{HTMLElement("menu")}}). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter. | | {{HTMLElement("menu")}} | 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). | | {{HTMLElement("ol")}} | Represents an ordered list of items — typically rendered as a numbered list. | | {{HTMLElement("p")}} | 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. | | {{HTMLElement("pre")}} | 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. | | {{HTMLElement("ul")}} | Represents an unordered list of items, typically rendered as a bulleted list. | ## Inline text semantics Use the HTML inline text semantic to define the meaning, structure, or style of a word, line, or any arbitrary piece of text. | Element | Description | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("a")}} | Together with its `href` attribute, creates a hyperlink to web pages, files, email addresses, locations within the current page, or anything else a URL can address. | | {{HTMLElement("abbr")}} | Represents an abbreviation or acronym. | | {{HTMLElement("b")}} | 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 strong element. | | {{HTMLElement("bdi")}} | 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. | | {{HTMLElement("bdo")}} | Overrides the current directionality of text, so that the text within is rendered in a different direction. | | {{HTMLElement("br")}} | Produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant. | | {{HTMLElement("cite")}} | 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. | | {{HTMLElement("code")}} | 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 user agent's default monospace font. | | {{HTMLElement("data")}} | Links a given piece of content with a machine-readable translation. If the content is time- or date-related, the`<time>` element must be used. | | {{HTMLElement("dfn")}} | Used to indicate the term being defined within the context of a definition phrase or sentence. The ancestor {{HTMLElement("p")}} element, the {{HTMLElement("dt")}}/{{HTMLElement("dd")}} pairing, or the nearest section ancestor of the `<dfn>` element, is considered to be the definition of the term. | | {{HTMLElement("em")}} | Marks text that has stress emphasis. The `<em>` element can be nested, with each nesting level indicating a greater degree of emphasis. | | {{HTMLElement("i")}} | Represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, and taxonomical designations, among others. Historically, these have been presented using italicized type, which is the original source of the `<i>` naming of this element. | | {{HTMLElement("kbd")}} | Represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. By convention, the user agent defaults to rendering the contents of a `<kbd>` element using its default monospace font, although this is not mandated by the HTML standard. | | {{HTMLElement("mark")}} | Represents text which is marked or highlighted for reference or notation purposes due to the marked passage's relevance in the enclosing context. | | {{HTMLElement("q")}} | Indicates that the enclosed text is a short inline quotation. Most modern browsers implement this by surrounding the text in quotation marks. This element is intended for short quotations that don't require paragraph breaks; for long quotations use the {{HTMLElement("blockquote")}} element. | | {{HTMLElement("rp")}} | Used to provide fall-back parentheses for browsers that do not support the 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. | | {{HTMLElement("rt")}} | 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. | | {{HTMLElement("ruby")}} | Represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common. | | {{HTMLElement("s")}} | Renders text with a strikethrough, or a line through it. Use the `<s>` element to represent things that are no longer relevant or no longer accurate. However, `<s>` is not appropriate when indicating document edits; for that, use the del and ins elements, as appropriate. | | {{HTMLElement("samp")}} | 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). | | {{HTMLElement("small")}} | Represents side-comments and small print, like copyright and legal text, independent of its styled presentation. By default, it renders text within it one font size smaller, such as from `small` to `x-small`. | | {{HTMLElement("span")}} | 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` or `id` attributes), or because they share attribute values, such as `lang`. It should be used only when no other semantic element is appropriate. `<span>` is very much like a div element, but 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). | | {{HTMLElement("strong")}} | Indicates that its contents have strong importance, seriousness, or urgency. Browsers typically render the contents in bold type. | | {{HTMLElement("sub")}} | Specifies inline text which should be displayed as subscript for solely typographical reasons. Subscripts are typically rendered with a lowered baseline using smaller text. | | {{HTMLElement("sup")}} | Specifies inline text which is to be displayed as superscript for solely typographical reasons. Superscripts are usually rendered with a raised baseline using smaller text. | | {{HTMLElement("time")}} | Represents a specific period in time. It may include the `datetime` attribute to translate dates into machine-readable format, allowing for better search engine results or custom features such as reminders. | | {{HTMLElement("u")}} | 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. | | {{HTMLElement("var")}} | Represents the name of a variable in a mathematical expression or a programming context. It's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent. | | {{HTMLElement("wbr")}} | 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. | ## Image and multimedia HTML supports various multimedia resources such as images, audio, and video. | Element | Description | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("area")}} | Defines an area inside an image map that has predefined clickable areas. An _image map_ allows geometric areas on an image to be associated with {{Glossary("Hyperlink", "hyperlink")}}. | | {{HTMLElement("audio")}} | 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 {{domxref("MediaStream")}}. | | {{HTMLElement("img")}} | Embeds an image into the document. | | {{HTMLElement("map")}} | Used with {{HTMLElement("area")}} elements to define an image map (a clickable link area). | | {{HTMLElement("track")}} | Used as a child of the media elements, audio and 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. | | {{HTMLElement("video")}} | Embeds a media player which supports video playback into the document. You can also use `<video>` for audio content, but the audio element may provide a more appropriate user experience. | ## Embedded content In addition to regular multimedia content, HTML can include a variety of other content, even if it's not always easy to interact with. | Element | Description | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("embed")}} | 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. | | {{HTMLElement("iframe")}} | Represents a nested browsing context, embedding another HTML page into the current one. | | {{HTMLElement("object")}} | Represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin. | | {{HTMLElement("picture")}} | Contains zero or more {{HTMLElement("source")}} elements and one {{HTMLElement("img")}} element to offer alternative versions of an image for different display/device scenarios. | | {{HTMLElement("portal")}} | Enables the embedding of another HTML page into the current one to enable smoother navigation into new pages. | | {{HTMLElement("source")}} | Specifies multiple media resources for the picture, the audio element, or the video element. It is a void element, meaning that it has no content and does not have a closing tag. It is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for [image file formats](/en-US/docs/Web/Media/Formats/Image_types) and [media file formats](/en-US/docs/Web/Media/Formats). | ## SVG and MathML You can embed [SVG](/en-US/docs/Web/SVG) and [MathML](/en-US/docs/Web/MathML) content directly into HTML documents, using the {{SVGElement("svg")}} and {{MathMLElement("math")}} elements. | Element | Description | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{SVGElement("svg")}} | Container defining a new coordinate system and [viewport](/en-US/docs/Web/SVG/Attribute/viewBox). It is used as the outermost element of SVG documents, but it can also be used to embed an SVG fragment inside an SVG or HTML document. | | {{MathMLElement("math")}} | The top-level element in MathML. Every valid MathML instance must be wrapped in it. In addition, you must not nest a second `<math>` element in another, but you can have an arbitrary number of other child elements in it. | ## Scripting To create dynamic content and Web applications, HTML supports the use of scripting languages, most prominently JavaScript. Certain elements support this capability. | Element | Description | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | {{HTMLElement("canvas")}} | Container element to use with either the [canvas scripting API](/en-US/docs/Web/API/Canvas_API) or the [WebGL API](/en-US/docs/Web/API/WebGL_API) to draw graphics and animations. | | {{HTMLElement("noscript")}} | Defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. | | {{HTMLElement("script")}} | Used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The `<script>` element can also be used with other languages, such as [WebGL](/en-US/docs/Web/API/WebGL_API)'s GLSL shader programming language and [JSON](/en-US/docs/Glossary/JSON). | ## Demarcating edits These elements let you provide indications that specific parts of the text have been altered. | Element | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("del")}} | Represents a range of text that has been deleted from a document. This can be used when rendering "track changes" or source code diff information, for example. The `<ins>` element can be used for the opposite purpose: to indicate text that has been added to the document. | | {{HTMLElement("ins")}} | Represents a range of text that has been added to a document. You can use the `<del>` element to similarly represent a range of text that has been deleted from the document. | ## Table content The elements here are used to create and handle tabular data. | Element | Description | | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("caption")}} | Specifies the caption (or title) of a table. | | {{HTMLElement("col")}} | Defines one or more columns in a column group represented by its implicit or explicit parent {{HTMLElement("colgroup")}} element. The `<col>` element is only valid as a child of a {{HTMLElement("colgroup")}} element that has no [`span`](/en-US/docs/Web/HTML/Element/colgroup#span) attribute defined. | | {{HTMLElement("colgroup")}} | Defines a group of columns within a table. | | {{HTMLElement("table")}} | Represents tabular data—that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. | | {{HTMLElement("tbody")}} | Encapsulates a set of table rows ({{HTMLElement("tr")}} elements), indicating that they comprise the body of a table's (main) data. | | {{HTMLElement("td")}} | A child of the {{HTMLElement("tr")}} element, it defines a cell of a table that contains data. | | {{HTMLElement("tfoot")}} | 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. | | {{HTMLElement("th")}} | A child of the {{HTMLElement("tr")}} element, it defines a cell as the header of a group of table cells. The nature of this group can be explicitly defined by the [`scope`](/en-US/docs/Web/HTML/Element/th#scope) and [`headers`](/en-US/docs/Web/HTML/Element/th#headers) attributes. | | {{HTMLElement("thead")}} | 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). | | {{HTMLElement("tr")}} | Defines a row of cells in a table. The row's cells can then be established using a mix of {{HTMLElement("td")}} (data cell) and {{HTMLElement("th")}} (header cell) elements. | ## Forms HTML provides several elements that can be used together to create forms that the user can fill out and submit to the website or application. Further information about this available in the [HTML forms guide](/en-US/docs/Learn/Forms). | Element | Description | | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("button")}} | An interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it performs an action, such as submitting a [form](/en-US/docs/Learn/Forms) or opening a dialog. | | {{HTMLElement("datalist")}} | Contains a set of {{HTMLElement("option")}} elements that represent the permissible or recommended options available to choose from within other controls. | | {{HTMLElement("fieldset")}} | Used to group several controls as well as labels ({{HTMLElement("label")}}) within a web form. | | {{HTMLElement("form")}} | Represents a document section containing interactive controls for submitting information. | | {{HTMLElement("input")}} | Used to create interactive controls for web-based forms to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and 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. | | {{HTMLElement("label")}} | Represents a caption for an item in a user interface. | | {{HTMLElement("legend")}} | Represents a caption for the content of its parent {{HTMLElement("fieldset")}}. | | {{HTMLElement("meter")}} | Represents either a scalar value within a known range or a fractional value. | | {{HTMLElement("optgroup")}} | Creates a grouping of options within a {{HTMLElement("select")}} element. | | {{HTMLElement("option")}} | Used to define an item contained in a 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. | | {{HTMLElement("output")}} | Container element into which a site or app can inject the results of a calculation or the outcome of a user action. | | {{HTMLElement("progress")}} | Displays an indicator showing the completion progress of a task, typically displayed as a progress bar. | | {{HTMLElement("select")}} | Represents a control that provides a menu of options. | | {{HTMLElement("textarea")}} | 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. | ## Interactive elements HTML offers a selection of elements that help to create interactive user interface objects. | Element | Description | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("details")}} | 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. | | {{HTMLElement("dialog")}} | Represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow. | | {{HTMLElement("summary")}} | Specifies a summary, caption, or legend for a details element's disclosure box. Clicking the `<summary>` element toggles the state of the parent {{HTMLElement("details")}} element open and closed. | ## Web Components Web Components is an HTML-related technology that makes it possible to, essentially, create and use custom elements as if it were regular HTML. In addition, you can create custom versions of standard HTML elements. | Element | Description | | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("slot")}} | Part of the [Web Components](/en-US/docs/Web/API/Web_components) technology suite, this element is a placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. | | {{HTMLElement("template")}} | A mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. | ## Obsolete and deprecated elements > **Warning:** These are old HTML elements that are deprecated and should not be used. **You should never use them in new projects, and you should replace them in old projects as soon as you can.** They are listed here for completeness only. | Element | Description | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{HTMLElement("acronym")}} | Allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. | | {{HTMLElement("big")}} | Renders the enclosed text at a font size one level larger than the surrounding text (`medium` becomes `large`, for example). The size is capped at the browser's maximum permitted font size. | | {{HTMLElement("center")}} | Displays its block-level or inline contents centered horizontally within its containing element. | | `<content>` | An obsolete part of the [Web Components](/en-US/docs/Web/API/Web_components) suite of technologies—was used inside of [Shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) as an insertion point, and wasn't meant to be used in ordinary HTML. It has now been replaced by the {{HTMLElement("slot")}} element, which creates a point in the DOM at which a shadow DOM can be inserted. Consider using {{HTMLElement("slot")}} instead. | | {{HTMLElement("dir")}} | Container for a directory of files and/or folders, potentially with styles and icons applied by the user agent. Do not use this obsolete element; instead, you should use the {{HTMLElement("ul")}} element for lists, including lists of files. | | {{HTMLElement("font")}} | Defines the font size, color and face for its content. | | {{HTMLElement("frame")}} | Defines a particular area in which another HTML document can be displayed. A frame should be used within a {{HTMLElement("frameset")}}. | | {{HTMLElement("frameset")}} | Used to contain {{HTMLElement("frame")}} elements. | | {{HTMLElement("image")}} | An ancient and poorly supported precursor to the {{HTMLElement("img")}} element. It should not be used. | | {{HTMLElement("marquee")}} | 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. | | {{HTMLElement("menuitem")}} | Represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button. | | {{HTMLElement("nobr")}} | 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. | | {{HTMLElement("noembed")}} | An obsolete, non-standard way to provide alternative, or "fallback", content for browsers that do not support the embed element or do not support the type of [embedded content](/en-US/docs/Web/HTML/Content_categories#embedded_content) an author wishes to use. This element was deprecated in HTML 4.01 and above in favor of placing fallback content between the opening and closing tags of an {{HTMLElement("object")}} element. | | {{HTMLElement("noframes")}} | 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. | | {{HTMLElement("param")}} | Defines parameters for an {{HTMLElement("object")}} element. | | {{HTMLElement("plaintext")}} | 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. | | {{HTMLElement("rb")}} | Used to delimit the base text component of a ruby annotation, i.e. the text that is being annotated. One `<rb>` element should wrap each separate atomic segment of the base text. | | {{HTMLElement("rtc")}} | 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. | | `<shadow>` | An obsolete part of the [Web Components](/en-US/docs/Web/API/Web_components) technology suite that was intended to be used as a shadow DOM insertion point. You might have used it if you have created multiple shadow roots under a shadow host. Consider using {{HTMLElement("slot")}} instead. | | {{HTMLElement("strike")}} | Places a strikethrough (horizontal line) over text. | | {{HTMLElement("tt")}} | Creates inline text which is presented using the user agent default monospace font face. This element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer. | | {{HTMLElement("xmp")}} | 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. | ## See also - {{DOMXref("Element")}} interface
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/br/index.md
--- title: "<br>: The Line Break element" slug: Web/HTML/Element/br page-type: html-element browser-compat: html.elements.br --- {{HTMLSidebar}} The **`<br>`** [HTML](/en-US/docs/Web/HTML) element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant. {{EmbedInteractiveExample("pages/tabbed/br.html", "tabbed-standard")}} As you can see from the above example, a `<br>` element is included at each point where we want the text to break. The text after the `<br>` begins again at the start of the next line of the text block. > **Note:** Do not use `<br>` to create margins between paragraphs; wrap them in {{htmlelement("p")}} elements and use the [CSS](/en-US/docs/Web/CSS) {{cssxref('margin')}} property to control their size. ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ### Deprecated attributes - `clear` {{Deprecated_Inline}} - : Indicates where to begin the next line after the break. ## Styling with CSS The `<br>` element has a single, well-defined purpose — to create a line break in a block of text. As such, it has no dimensions or visual output of its own, and there is very little you can do to style it. You can set a {{cssxref("margin")}} on `<br>` elements themselves to increase the spacing between the lines of text in the block, but this is a bad practice — you should use the {{cssxref("line-height")}} property that was designed for that purpose. ## Examples ### Simple br In the following example we use `<br>` elements to create line breaks between the different lines of a postal address: ```html Mozilla<br /> 331 E. Evelyn Avenue<br /> Mountain View, CA<br /> 94041<br /> USA<br /> ``` #### Result {{ EmbedLiveSample('Simple_br', 640, 120) }} ## Accessibility concerns Creating separate paragraphs of text using `<br>` is not only bad practice, it is problematic for people who navigate with the aid of screen reading technology. Screen readers may announce the presence of the element, but not any content contained within `<br>`s. This can be a confusing and frustrating experience for the person using the screen reader. Use `<p>` elements, and use CSS properties like {{cssxref("margin")}} to control their spacing. ## 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>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. In XHTML documents, write this element as <code>&#x3C;br /></code>. </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> <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("HTMLBRElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("address")}} element - {{HTMLElement("p")}} element - {{HTMLElement("wbr")}} element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/area/index.md
--- title: "<area>: The Image Map Area element" slug: Web/HTML/Element/area page-type: html-element browser-compat: html.elements.area --- {{HTMLSidebar}} The **`<area>`** [HTML](/en-US/docs/Web/HTML) element defines an area inside an image map that has predefined clickable areas. An _image map_ allows geometric areas on an image to be associated with {{Glossary("Hyperlink", "hypertext links")}}. This element is used only within a {{HTMLElement("map")}} element. {{EmbedInteractiveExample("pages/tabbed/area.html", "tabbed-taller")}} ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `alt` - : A text string alternative to display on browsers that do not display images. The text should be phrased so that it presents the user with the same kind of choice as the image would offer when displayed without the alternative text. This attribute is required only if the [`href`](#href) attribute is used. - `coords` - : The `coords` attribute details the coordinates of the [`shape`](#shape) attribute in size, shape, and placement of an `<area>`. This attribute must not be used if `shape` is set to `default`. - `rect`: the value is `x1,y1,x2,y2`. The value specifies the coordinates of the top-left and bottom-right corner of the rectangle. For example, in `<area shape="rect" coords="0,0,253,27" href="#" target="_blank" alt="Mozilla">` the coordinates are `0,0` and `253,27`, indicating the top-left and bottom-right corners of the rectangle, respectively. - `circle`: the value is `x,y,radius`. Value specifies the coordinates of the circle center and the radius. For example: `<area shape="circle" coords="130,136,60" href="#" target="_blank" alt="MDN">` - `poly`: the value is `x1,y1,x2,y2,..,xn,yn`. Value specifies the coordinates of the edges of the polygon. If the first and last coordinate pairs are not the same, the browser will add the last coordinate pair to close the polygon The values are numbers of CSS pixels. - `download` - : This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. See {{HTMLElement("a")}} for a full description of the [`download`](/en-US/docs/Web/HTML/Element/a#download) attribute. - `href` - : The hyperlink target for the area. Its value is a valid URL. This attribute may be omitted; if so, the `<area>` element does not represent a hyperlink. - `ping` - : Contains a space-separated list of URLs to which, when the hyperlink is followed, {{HTTPMethod("POST")}} requests with the body `PING` will be sent by the browser (in the background). Typically used for tracking. - `referrerpolicy` - : A string indicating which referrer to use when fetching the resource: - `no-referrer`: The {{HTTPHeader("Referer")}} header will not be sent. - `no-referrer-when-downgrade`: The {{HTTPHeader("Referer")}} header will not be sent to {{Glossary("origin")}}s without {{Glossary("TLS")}} ({{Glossary("HTTPS")}}). - `origin`: The sent referrer will be limited to the origin of the referring page: its [scheme](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL), {{Glossary("host")}}, and {{Glossary("port")}}. - `origin-when-cross-origin`: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path. - `same-origin`: A referrer will be sent for {{Glossary("Same-origin policy", "same origin")}}, but cross-origin requests will contain no referrer information. - `strict-origin`: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP). - `strict-origin-when-cross-origin` (default): Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP). - `unsafe-url`: The referrer will include the origin _and_ the path (but not the [fragment](/en-US/docs/Web/API/HTMLAnchorElement/hash), [password](/en-US/docs/Web/API/HTMLAnchorElement/password), or [username](/en-US/docs/Web/API/HTMLAnchorElement/username)). **This value is unsafe**, because it leaks origins and paths from TLS-protected resources to insecure origins. - `rel` - : For anchors containing the [`href`](#href) attribute, this attribute specifies the relationship of the target object to the link object. The value is a space-separated list of link types. The values and their semantics will be registered by some authority that might have meaning to the document author. The default relationship, if no other is given, is void. Use this attribute only if the [`href`](#href) attribute is present. - `shape` - : The shape of the associated hot spot. The specifications for HTML defines the values `rect`, which defines a rectangular region; `circle`, which defines a circular region; `poly`, which defines a polygon; and `default`, which indicates the entire region beyond any defined shapes. - `target` - : A keyword or author-defined name of the {{Glossary("browsing context")}} to display the linked resource. The following keywords have special meanings: - `_self` (default): Show the resource in the current browsing context. - `_blank`: Show the resource in a new, unnamed browsing context. - `_parent`: Show the resource 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 resource 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`. Use this attribute only if the [`href`](#href) attribute is present. > **Note:** Setting `target="_blank"` on `<area>` elements implicitly provides the same `rel` behavior as setting [`rel="noopener"`](/en-US/docs/Web/HTML/Attributes/rel/noopener) which does not set `window.opener`. See [browser compatibility](#browser_compatibility) for support status. ## Examples ```html <map name="primary"> <area shape="circle" coords="75,75,75" href="left.html" alt="Click to go Left" /> <area shape="circle" coords="275,75,75" href="right.html" alt="Click to go Right" /> </map> <img usemap="#primary" src="https://via.placeholder.com/350x150" alt="350 x 150 pic" /> ``` ### Result {{ EmbedLiveSample('Examples', 360, 160) }} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories">Content categories</a> </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content">Flow content</a>, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content">phrasing content</a>. </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>. The <code>&#x3C;area></code> element must have an ancestor {{HTMLElement("map")}}, but it need not be a direct parent. </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> when <a href="/en-US/docs/Web/HTML/Element/area#href"><code>href</code></a> attribute is present, otherwise <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role"><code>generic</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("HTMLAreaElement")}}</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/aside/index.md
--- title: "<aside>: The Aside element" slug: Web/HTML/Element/aside page-type: html-element browser-compat: html.elements.aside --- {{HTMLSidebar}} The **`<aside>`** [HTML](/en-US/docs/Web/HTML) element represents a portion of a document whose content is only indirectly related to the document's main content. Asides are frequently presented as sidebars or call-out boxes. {{EmbedInteractiveExample("pages/tabbed/aside.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Do not use the `<aside>` element to tag parenthesized text, as this kind of text is considered part of the main flow. ## Examples ### Using \<aside> This example uses `<aside>` to mark up a paragraph in an article. The paragraph is only indirectly related to the main article content: ```html <article> <p> The Disney movie <cite>The Little Mermaid</cite> was first released to theatres in 1989. </p> <aside> <p>The movie earned $87 million during its initial release.</p> </aside> <p>More info about the movie…</p> </article> ``` #### Result {{EmbedLiveSample("Using_aside")}} ## 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;aside></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/Complementary_role" >complementary</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/feed_role"><code>feed</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/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 section-related elements: {{HTMLElement("body")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}}, {{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: Complementary role](/en-US/docs/Web/Accessibility/ARIA/Roles/complementary_role)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/body/index.md
--- title: "<body>: The Document Body element" slug: Web/HTML/Element/body page-type: html-element browser-compat: html.elements.body --- {{HTMLSidebar}} The **`<body>`** [HTML](/en-US/docs/Web/HTML) element represents the content of an HTML document. There can be only one `<body>` element in a document. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `alink` {{deprecated_inline}} - : Color of text for hyperlinks when selected. **Do not use this attribute! Use the CSS {{cssxref("color")}} property in conjunction with the {{cssxref(":active")}} pseudo-class instead.** - `background` {{deprecated_inline}} - : URI of an image to use as a background. **Do not use this attribute! Use the CSS {{cssxref("background")}} property on the element instead.** - `bgcolor` {{deprecated_inline}} - : Background color for the document. **Do not use this attribute! Use the CSS {{cssxref("background-color")}} property on the element instead.** - `bottommargin` {{deprecated_inline}} - : The margin of the bottom of the body. **Do not use this attribute! Use the CSS {{cssxref("margin-bottom")}} property on the element instead.** - `leftmargin` {{deprecated_inline}} - : The margin of the left of the body. **Do not use this attribute! Use the CSS {{cssxref("margin-left")}} property on the element instead.** - `link` {{deprecated_inline}} - : Color of text for unvisited hypertext links. **Do not use this attribute! Use the CSS {{cssxref("color")}} property in conjunction with the {{cssxref(":link")}} pseudo-class instead.** - `onafterprint` - : Function to call after the user has printed the document. - `onbeforeprint` - : Function to call when the user requests printing of the document. - `onbeforeunload` - : Function to call when the document is about to be unloaded. - `onblur` - : Function to call when the document loses focus. - `onerror` - : Function to call when the document fails to load properly. - `onfocus` - : Function to call when the document receives focus. - `onhashchange` - : Function to call when the fragment identifier part (starting with the hash (`'#'`) character) of the document's current address has changed. - `onlanguagechange` - : Function to call when the preferred languages changed. - `onload` - : Function to call when the document has finished loading. - `onmessage` - : Function to call when the document has received a message. - `onoffline` - : Function to call when network communication has failed. - `ononline` - : Function to call when network communication has been restored. - `onpopstate` - : Function to call when the user has navigated session history. - `onredo` - : Function to call when the user has moved forward in undo transaction history. - `onresize` - : Function to call when the document has been resized. - `onstorage` - : Function to call when the storage area has changed. - `onundo` - : Function to call when the user has moved backward in undo transaction history. - `onunload` - : Function to call when the document is going away. - `rightmargin` {{deprecated_inline}} - : The margin of the right of the body. **Do not use this attribute! Use the CSS {{cssxref("margin-right")}} property on the element instead.** - `text` {{deprecated_inline}} - : Foreground color of text. **Do not use this attribute! Use CSS {{cssxref("color")}} property on the element instead.** - `topmargin` {{deprecated_inline}} - : The margin of the top of the body. **Do not use this attribute! Use the CSS {{cssxref("margin-top")}} property on the element instead.** - `vlink` {{deprecated_inline}} - : Color of text for visited hypertext links. **Do not use this attribute! Use the CSS {{cssxref("color")}} property in conjunction with the {{cssxref(":visited")}} pseudo-class instead.** ## Examples ```html <html lang="en"> <head> <title>Document title</title> </head> <body> <p> The <code>&lt;body&gt;</code> HTML element represents the content of an HTML document. There can be only one <code>&lt;body&gt;</code> element in a document. </p> </body> </html> ``` ### 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> None. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag may be omitted if the first thing inside it is not a space character, comment, {{HTMLElement("script")}} element or {{HTMLElement("style")}} element. The end tag may be omitted if the <code>&#x3C;body></code> element has contents or has a start tag, and is not immediately followed by a comment. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> It must be the second element of an {{HTMLElement("html")}} 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>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td> {{domxref("HTMLBodyElement")}} <ul> <li> The <code>&#x3C;body></code> element exposes the {{domxref("HTMLBodyElement")}} interface. </li> <li> You can access the <code>&#x3C;body></code> element through the {{domxref("document.body")}} property. </li> </ul> </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("html")}} - {{HTMLElement("head")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/li/index.md
--- title: "<li>: The List Item element" slug: Web/HTML/Element/li page-type: html-element browser-compat: html.elements.li --- {{HTMLSidebar}} The **`<li>`** [HTML](/en-US/docs/Web/HTML) element is used to represent an item in a list. It must be contained in a parent element: an ordered list ({{HTMLElement("ol")}}), an unordered list ({{HTMLElement("ul")}}), or a menu ({{HTMLElement("menu")}}). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter. {{EmbedInteractiveExample("pages/tabbed/li.html", "tabbed-shorter")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `value` - : This integer attribute indicates the current ordinal value of the list item as defined by the {{HTMLElement("ol")}} element. The only allowed value for this attribute is a number, even if the list is displayed with Roman numerals or letters. List items that follow this one continue numbering from the value set. The **value** attribute has no meaning for unordered lists ({{HTMLElement("ul")}}) or for menus ({{HTMLElement("menu")}}). - `type` {{Deprecated_inline}} {{Non-standard_Inline}} - : This character attribute indicates the numbering type: - `a`: lowercase letters - `A`: uppercase letters - `i`: lowercase Roman numerals - `I`: uppercase Roman numerals - `1`: numbers This type overrides the one used by its parent {{HTMLElement("ol")}} element, if any. > **Note:** This attribute has been deprecated; use the CSS {{cssxref("list-style-type")}} property instead. ## Examples For more detailed examples, see the {{htmlelement("ol")}} and {{htmlelement("ul")}} pages. ### Ordered list ```html <ol> <li>first item</li> <li>second item</li> <li>third item</li> </ol> ``` #### Result {{EmbedLiveSample("Ordered_list")}} ### Ordered list with a custom value ```html <ol type="I"> <li value="3">third item</li> <li>fourth item</li> <li>fifth item</li> </ol> ``` #### Result {{EmbedLiveSample("Ordered_list_with_a_custom_value")}} ### Unordered list ```html <ul> <li>first item</li> <li>second item</li> <li>third item</li> </ul> ``` #### Result {{EmbedLiveSample("Unordered_list")}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The end tag can be omitted if the list item is immediately followed by another {{HTMLElement("li")}} element, or if there is no more content in its parent element. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> An {{HTMLElement("ul")}}, {{HTMLElement("ol")}}, or {{HTMLElement("menu")}} element. Though not a conforming usage, the obsolete {{HTMLElement("dir")}} can also be a parent. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Listitem_role" >listitem</a ></code > when child of an <code><a href="/en-US/docs/Web/HTML/Element/ol">ol</a></code >, <code><a href="/en-US/docs/Web/HTML/Element/ul">ul</a></code> or <code><a href="/en-US/docs/Web/HTML/Element/menu">menu</a></code> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <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/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/radio_role"><code>radio</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/separator_role"><code>separator</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role"><code>tab</code></a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/treeitem_role"><code>treeitem</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLLIElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other list-related HTML Elements: {{HTMLElement("ul")}}, {{HTMLElement("ol")}}, {{HTMLElement("menu")}}, and the obsolete {{HTMLElement("dir")}}; - CSS properties that may be specially useful to style the `<li>` element: - the {{cssxref("list-style")}} property, to choose the way the ordinal is displayed, - [CSS counters](/en-US/docs/Web/CSS/CSS_counter_styles/Using_CSS_counters), to handle complex nested lists, - the {{cssxref("margin")}} property, to control the indent of the list item.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/abbr/index.md
--- title: "<abbr>: The Abbreviation element" slug: Web/HTML/Element/abbr page-type: html-element browser-compat: html.elements.abbr --- {{HTMLSidebar}} The **`<abbr>`** [HTML](/en-US/docs/Web/HTML) element represents an abbreviation or acronym. When including an abbreviation or acronym, provide a full expansion of the term in plain text on first use, along with the `<abbr>` to mark up the abbreviation. This informs the user what the abbreviation or acronym means. The optional [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute can provide an expansion for the abbreviation or acronym when a full expansion is not present. This provides a hint to user agents on how to announce/display the content while informing all users what the abbreviation means. If present, `title` must contain this full description and nothing else. {{EmbedInteractiveExample("pages/tabbed/abbr.html", "tabbed-shorter")}} ## Attributes This element only supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). The [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute has a specific semantic meaning when used with the `<abbr>` element; it _must_ contain a full human-readable description or expansion of the abbreviation. This text is often presented by browsers as a tooltip when the mouse cursor is hovered over the element. Each `<abbr>` element you use is independent of all others; providing a `title` for one does not automatically attach the same expansion text to others with the same content text. ## Usage notes ### Typical use cases It's certainly not required that all abbreviations be marked up using `<abbr>`. There are, though, a few cases where it's helpful to do so: - When an abbreviation is used and you want to provide an expansion or definition outside the flow of the document's content, use `<abbr>` with an appropriate [`title`](/en-US/docs/Web/HTML/Global_attributes#title). - To define an abbreviation which may be unfamiliar to the reader, present the term using `<abbr>` and inline text providing the definition. Include a `title` attribute only when the inline expansion or definition is not available. - When an abbreviation's presence in the text needs to be semantically noted, the `<abbr>` element is useful. This can be used, in turn, for styling or scripting purposes. - You can use `<abbr>` in concert with {{HTMLElement("dfn")}} to establish definitions for terms which are abbreviations or acronyms. See the example [Defining an abbreviation](#defining_an_abbreviation) below. ### Grammar considerations In languages with [grammatical number](https://en.wikipedia.org/wiki/Grammatical_number) (that is, languages where the number of items affects the grammar of a sentence), use the same grammatical number in your `title` attribute as inside your `<abbr>` element. This is especially important in languages with more than two numbers, such as Arabic, but is also relevant in English. ## Default styling The purpose of this element is purely for the convenience of the author and all browsers display it inline ({{cssxref('display')}}`: inline`) by default, though its default styling varies from one browser to another: Some browsers add a dotted underline to the content of the element. Others add a dotted underline while converting the contents to small caps. Others may not style it differently than a {{HTMLElement("span")}} element. To control this styling, use {{cssxref('text-decoration')}} and {{cssxref('font-variant')}}. ## Examples ### Marking up an abbreviation semantically To mark up an abbreviation without providing an expansion or description, use `<abbr>` without any attributes, as seen in this example. #### HTML ```html <p>Using <abbr>HTML</abbr> is fun and easy!</p> ``` #### Result {{EmbedLiveSample("Marking_up_an_abbreviation_semantically")}} ### Styling abbreviations You can use CSS to set a custom style to be used for abbreviations, as seen in this simple example. #### HTML ```html <p>Using <abbr>CSS</abbr>, you can style your abbreviations!</p> ``` #### CSS ```css abbr { font-variant: all-small-caps; } ``` #### Result {{EmbedLiveSample("Styling_abbreviations")}} ### Providing an expansion Adding a [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute lets you provide an expansion or definition for the abbreviation or acronym. #### HTML ```html <p>Ashok's joke made me <abbr title="Laugh Out Loud">LOL</abbr> big time.</p> ``` #### Result {{EmbedLiveSample("Providing_an_expansion")}} ### Defining an abbreviation You can use `<abbr>` in tandem with {{HTMLElement("dfn")}} to more formally define an abbreviation, as shown here. #### HTML ```html <p> <dfn id="html"><abbr title="HyperText Markup Language">HTML</abbr> </dfn> is a markup language used to create the semantics and structure of a web page. </p> <p> A <dfn id="spec">Specification</dfn> (<abbr>spec</abbr>) is a document that outlines in detail how a technology or API is intended to function and how it is accessed. </p> ``` #### Result {{EmbedLiveSample("Defining_an_abbreviation", 600, 120)}} ### Accessibility concerns Spelling out the acronym or abbreviation in full the first time it is used on a page is beneficial for helping people understand it, especially if the content is technical or industry jargon. Only include a `title` if expanding the abbreviation or acronym in the text is not possible. Having a difference between the announced word or phrase and what is displayed on the screen, especially if it's technical jargon the reader may not be familiar with, can be jarring. #### HTML ```html <p> JavaScript Object Notation (<abbr>JSON</abbr>) is a lightweight data-interchange format. </p> ``` #### Result {{EmbedLiveSample("Accessibility_concerns")}} This is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >, palpable content </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >Phrasing content</a > </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Any element that accepts <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a > </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM Interface</th> <td>{{domxref("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the `<abbr>` element](/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting#abbreviations)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/figcaption/index.md
--- title: "<figcaption>: The Figure Caption element" slug: Web/HTML/Element/figcaption page-type: html-element browser-compat: html.elements.figcaption --- {{HTMLSidebar}} The **`<figcaption>`** [HTML](/en-US/docs/Web/HTML) element represents a caption or legend describing the rest of the contents of its parent {{HTMLElement("figure")}} element, providing the `<figure>` an {{glossary("accessible description")}}. {{EmbedInteractiveExample("pages/tabbed/figcaption.html","tabbed-shorter")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples Please see the {{HTMLElement("figure")}} page for examples on `<figcaption>`. ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>{{no_tag_omission}}</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("figure")}} element; the <code>&#x3C;figcaption></code> element must be its first or last 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> <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> </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("figure")}} element.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/ul/index.md
--- title: "<ul>: The Unordered List element" slug: Web/HTML/Element/ul page-type: html-element browser-compat: html.elements.ul --- {{HTMLSidebar}} The **`<ul>`** [HTML](/en-US/docs/Web/HTML) element represents an unordered list of items, typically rendered as a bulleted list. {{EmbedInteractiveExample("pages/tabbed/ul.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `compact` {{Deprecated_inline}} - : This Boolean attribute hints that the list should be rendered in a compact style. The interpretation of this attribute depends on the {{glossary("user agent")}}, and it doesn't work in all browsers. > **Warning:** Do not use this attribute, as it has been deprecated: use [CSS](/en-US/docs/Web/CSS) instead. To give a similar effect as the `compact` attribute, the CSS property {{cssxref("line-height")}} can be used with a value of `80%`. - `type` {{Deprecated_inline}} - : This attribute sets the bullet style for the list. The values defined under HTML3.2 and the transitional version of HTML 4.0/4.01 are: - `circle` - `disc` - `square` A fourth bullet type has been defined in the WebTV interface, but not all browsers support it: `triangle`. If not present and if no [CSS](/en-US/docs/Web/CSS) {{ cssxref("list-style-type") }} property applies to the element, the user agent selects a bullet type depending on the nesting level of the list. > **Warning:** Do not use this attribute, as it has been deprecated; use the [CSS](/en-US/docs/Web/CSS) {{ cssxref("list-style-type") }} property instead. ## Usage notes - The `<ul>` element is for grouping a collection of items that do not have a numerical ordering, and their order in the list is meaningless. Typically, unordered-list items are displayed with a bullet, which can be of several forms, like a dot, a circle, or a square. The bullet style is not defined in the HTML description of the page, but in its associated CSS, using the {{ cssxref("list-style-type") }} property. - The `<ul>` and {{HTMLElement("ol")}} elements may be nested as deeply as desired. Moreover, the nested lists may alternate between `<ol>` and `<ul>` without restriction. - The {{ HTMLElement("ol") }} and `<ul>` elements both represent a list of items. They differ in that, with the {{ HTMLElement("ol") }} element, the order is meaningful. To determine which one to use, try changing the order of the list items; if the meaning is changed, the {{ HTMLElement("ol") }} element should be used, otherwise you can use `<ul>`. ## Examples ### Simple example ```html <ul> <li>first item</li> <li>second item</li> <li>third item</li> </ul> ``` #### Result {{EmbedLiveSample("Simple_example", 400, 120)}} ### Nesting a list ```html <ul> <li>first item</li> <li> second item <!-- Look, the closing </li> tag is not placed here! --> <ul> <li>second item first subitem</li> <li> second item second subitem <!-- Same for the second nested unordered list! --> <ul> <li>second item second subitem first sub-subitem</li> <li>second item second subitem second sub-subitem</li> <li>second item second subitem third sub-subitem</li> </ul> </li> <!-- Closing </li> tag for the li that contains the third unordered list --> <li>second item third subitem</li> </ul> <!-- Here is the closing </li> tag --> </li> <li>third item</li> </ul> ``` #### Result {{EmbedLiveSample("Nesting_a_list", 400, 340)}} ### Ordered list inside unordered list ```html <ul> <li>first item</li> <li> second item <!-- Look, the closing </li> tag is not placed here! --> <ol> <li>second item first subitem</li> <li>second item second subitem</li> <li>second item third subitem</li> </ol> <!-- Here is the closing </li> tag --> </li> <li>third item</li> </ul> ``` #### Result {{EmbedLiveSample("Ordered_list_inside_unordered_list", 400, 190)}} ## 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;ul></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("HTMLUListElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other list-related HTML Elements: {{HTMLElement("ol")}}, {{HTMLElement("li")}}, {{HTMLElement("menu")}} - CSS properties that may be specially useful to style the `<ul>` 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`](#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/source/index.md
--- title: "<source>: The Media or Image Source element" slug: Web/HTML/Element/source page-type: html-element browser-compat: html.elements.source --- {{HTMLSidebar}} The **`<source>`** [HTML](/en-US/docs/Web/HTML) element specifies one or more media resources for the {{HTMLElement("picture")}}, {{HTMLElement("audio")}}, and {{HTMLElement("video")}} elements. It is a {{glossary("void element")}}, which means that it has no content and does not require a closing tag. This element is commonly used to offer the same media content in multiple file formats in order to provide compatibility with a broad range of browsers given their differing support for [image file formats](/en-US/docs/Web/Media/Formats/Image_types) and [media file formats](/en-US/docs/Web/Media/Formats). {{EmbedInteractiveExample("pages/tabbed/source.html", "tabbed-standard")}} ## Attributes This element supports all [global attributes](/en-US/docs/Web/HTML/Global_attributes). In addition, the following attributes can be used with it: - `type` - : Specifies the [MIME media type of the image](/en-US/docs/Web/Media/Formats/Image_types) or [other media type](/en-US/docs/Web/Media/Formats/Containers), optionally including a [`codecs` parameter](/en-US/docs/Web/Media/Formats/codecs_parameter). - `src` - : Specifies the URL of the media resource. Required if the parent of `<source>` is {{HTMLElement("audio")}} or {{HTMLElement("video")}}. Not allowed if the parent is {{HTMLElement("picture")}}. - `srcset` - : Specifies a comma-separated list of one or more image URLs and their descriptors. Required if the parent of `<source>` is {{HTMLElement("picture")}}. Not allowed if the parent is {{HTMLElement("audio")}} or {{HTMLElement("video")}}. The list consists of strings separated by commas, indicating a set of possible images for the browser to use. Each string is composed of: - A URL specifying an image location. - An optional width descriptor—a positive integer directly followed by `"w"`, such as `300w`. - An optional pixel density descriptor—a positive floating number directly followed by `"x"`, such as `2x`. Each string in the list must have either a width descriptor or a pixel density descriptor to be valid. These two descriptors should not be used together; only one should be used consistently throughout the list. The value of each descriptor in the list must be unique. The browser chooses the most adequate image to display at a given point of time based on these descriptors. If the descriptors are not specified, the default value used is `1x`. If the `sizes` attribute is also present, then each string must include a width descriptor. If the browser does not support `srcset`, then `src` will be used for the default image source. - `sizes` - : Specifies a list of source sizes that describe the final rendered width of the image. Allowed if the parent of `<source>` is {{HTMLElement("picture")}}. Not allowed if the parent is {{HTMLElement("audio")}} or {{HTMLElement("video")}}. The list consists of source sizes separated by commas. Each source size is media condition-length pair. Before laying the page out, the browser uses this information to determine which image defined in [`srcset`](#srcset) to display. Note that `sizes` will take effect only if width descriptors are provided with `srcset`, not pixel density descriptors (i.e., `200w` should be used instead of `2x`). - `media` - : Specifies the [media query](/en-US/docs/Web/CSS/CSS_media_queries) for the resource's intended media. - `height` - : Specifies the intrinsic height of the image in pixels. Allowed if the parent of `<source>` is a {{HTMLElement("picture")}}. Not allowed if the parent is {{HTMLElement("audio")}} or {{HTMLElement("video")}}. The height value must be an integer without any units. - `width` - : Specifies the intrinsic width of the image in pixels. Allowed if the parent of `<source>` is a {{HTMLElement("picture")}}. Not allowed if the parent is {{HTMLElement("audio")}} or {{HTMLElement("video")}}. The width value must be an integer without any units. ## Usage notes The `<source>` element is a **{{glossary("void element")}}**, which means that it not only has no content but also has no closing tag. That is, you _never_ use "`</source>`" in your HTML. The browser goes through a list of `<source>` elements to find a format it supports. It uses the first one it can display. For each `<source>` element: - If the `type` attribute isn't specified, the browser retrieves the media's type from the server and determines if it can be displayed. If the media can't be rendered, the browser checks the next `<source>` in the list. - If the `type` attribute is specified, the browser immediately compares it with the media types it can display. If the type is not supported, the browser skips querying the server and directly checks the next `<source>` element. If none of the `<source>` elements provide a usable source: - In the case of a `<picture>` element, the browser will fall back to using the image specified in the `<picture>` element's {{HTMLElement("img")}} child. - In the case of an `<audio>` or `<video>` element, the browser will fall back to displaying the content included between the element's opening and closing tags. For information about image formats supported by web browsers and guidance on selecting appropriate formats to use, see our [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types). For details on the video and audio media types you can use, see the [Media type and format guide](/en-US/docs/Web/Media/Formats). ## Examples ### Using the `type` attribute with `<video>` This example demonstrates how to offer a video in different formats: WebM for browsers that support it, Ogg for those that support Ogg, and QuickTime for browsers that support QuickTime. If the `<audio>` or `<video>` element is not supported by the browser, a notice is displayed instead. If the browser supports the element but does not support any of the specified formats, an `error` event is raised and the default media controls (if enabled) will indicate an error. For more details on which media file formats to use and their browser support, refer to our [Media type and format guide](/en-US/docs/Web/Media/Formats). ```html <video controls> <source src="foo.webm" type="video/webm" /> <source src="foo.ogg" type="video/ogg" /> <source src="foo.mov" type="video/quicktime" /> I'm sorry; your browser doesn't support HTML video. </video> ``` ### Using the `media` attribute with `<video>` This example demonstrates how to offer an alternate source file for viewports above a certain width. When a user's browsing environment meets the specified `media` condition, the associated `<source>` element is chosen. The contents of its `src` attribute are then requested and rendered. If the `media` condition does not match, the browser will move on to the next `<source>` in the list. The second `<source>` option in the code below has no `media` condition, so it will be selected for all other browsing contexts. ```html <video controls> <source src="foo-large.webm" media="(min-width: 800px)" /> <source src="foo.webm" /> I'm sorry; your browser doesn't support HTML video. </video> ``` For more examples, the [Video and audio content](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content) article in the Learn area is a great resource. ### Using the `media` attribute with `<picture>` In this example, two `<source>` elements are included within {{HTMLElement("picture")}}, providing versions of an image to use when the available space exceeds certain widths. If the available width is less than the smallest of these widths, the browser will fall back to the image specified in the {{HTMLElement("img")}} element. ```html <picture> <source srcset="mdn-logo-wide.png" media="(min-width: 800px)" /> <source srcset="mdn-logo-medium.png" media="(min-width: 600px)" /> <img src="mdn-logo-narrow.png" alt="MDN Web Docs" /> </picture> ``` With the `<picture>` element, you must always include an `<img>` with a fallback image. Also, make sure to add an `alt` attribute for accessibility, unless the image is purely decorative and irrelevant to the content. ### Using `height` and `width` attributes with `<picture>` In this example, three `<source>` elements with `height` and `width` attributes are included in a {{HTMLElement("picture")}} element. A [media query](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) allows the browser to select an image to display with the `height` and `width` attributes based on the [viewport](/en-US/docs/Glossary/Viewport) size. ```html <picture> <source srcset="landscape.png" media="(min-width: 1000px)" width="1000" height="400" /> <source srcset="square.png" media="(min-width: 800px)" width="800" height="800" /> <source srcset="portrait.png" media="(min-width: 600px)" width="600" height="800" /> <img src="fallback.png" alt="Image used when the browser does not support the sources" width="500" height="400" /> </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>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td>None; it is a {{Glossary("void element")}}.</td> </tr> <tr> <th scope="row">Tag omission</th> <td>It must have a start tag, but must not have an end tag.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> <div> A media element—{{HTMLElement("audio")}} or {{HTMLElement("video")}}—and it must be placed before any <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a > or {{HTMLElement("track")}} element. </div> <div> A {{HTMLElement("picture")}} element, and it must be placed before the {{HTMLElement("img")}} element. </div> </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("HTMLSourceElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("audio")}} element - {{HTMLElement("picture")}} element - {{HTMLElement("video")}} element - [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types) - [Media type and format guide](/en-US/docs/Web/Media/Formats) - [Web performance](/en-US/docs/Learn/Performance)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/dir/index.md
--- title: "<dir>: The Directory element" slug: Web/HTML/Element/dir page-type: html-element status: - deprecated browser-compat: html.elements.dir --- {{HTMLSidebar}}{{Deprecated_Header}} The **`<dir>`** [HTML](/en-US/docs/Web/HTML) element is used as a container for a directory of files and/or folders, potentially with styles and icons applied by the {{Glossary("user agent")}}. Do not use this obsolete element; instead, you should use the {{HTMLElement("ul")}} element for lists, including lists of files. > **Warning:** Do not use this element. Though present in early HTML specifications, it has been deprecated in HTML 4, and has since been removed entirely. ## DOM interface This element implements the {{domxref("HTMLDirectoryElement")}} interface. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `compact` {{Deprecated_Inline}} - : This Boolean attribute hints that the list should be rendered in a compact style. The interpretation of this attribute depends on the user agent and it doesn't work in all browsers. <!-- ## Technical summary --> ## Specifications Not part of any current specifications. ## Browser compatibility {{Compat}} ## See also - Other list-related HTML Elements: {{HTMLElement("ol")}}, {{HTMLElement("ul")}}, {{HTMLElement("li")}}, and {{HTMLElement("menu")}}; - CSS properties that may be specially useful to style the `<dir>` element: - The {{cssxref('list-style')}} property, useful to choose the way the ordinal is displayed. - [CSS counters](/en-US/docs/Web/CSS/CSS_counter_styles/Using_CSS_counters), useful to handle complex nested lists. - The {{Cssxref('line-height')}} property, useful to simulate the deprecated [`compact`](#compact) attribute. - The {{cssxref('margin')}} property, useful to control the indent of the list.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/blockquote/index.md
--- title: "<blockquote>: The Block Quotation element" slug: Web/HTML/Element/blockquote page-type: html-element browser-compat: html.elements.blockquote --- {{HTMLSidebar}} The **`<blockquote>`** [HTML](/en-US/docs/Web/HTML) element indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see [Notes](#usage_notes) for how to change it). A URL for the source of the quotation may be given using the `cite` attribute, while a text representation of the source can be given using the {{HTMLElement("cite")}} element. {{EmbedInteractiveExample("pages/tabbed/blockquote.html","tabbed-standard")}} ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `cite` - : A URL that designates a source document or message for the information quoted. This attribute is intended to point to information explaining the context or the reference for the quote. ## Usage notes To change the indentation applied to the quoted text, use the {{Glossary("CSS")}} {{cssxref("margin-left")}} and/or {{cssxref("margin-right")}} properties, or the {{cssxref("margin")}} shorthand property. To include shorter quotes inline rather than in a separate block, use the {{HTMLElement("q")}} (Quotation) element. ## Examples This example demonstrates the use of the `<blockquote>` element to quote a passage from {{RFC(1149)}}, _A Standard for the Transmission of IP Datagrams on Avian Carriers_. ```html <blockquote cite="https://datatracker.ietf.org/doc/html/rfc1149"> <p> Avian carriers can provide high delay, low throughput, and low altitude service. The connection topology is limited to a single point-to-point path for each carrier, used with standard carriers, but many carriers can be used without significant interference with each other, outside early spring. This is because of the 3D ether space available to the carriers, in contrast to the 1D ether used by IEEE802.3. The carriers have an intrinsic collision avoidance system, which increases availability. </p> </blockquote> ``` ### Result {{EmbedLiveSample("Examples", 640, 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> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >, sectioning root, 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 >. </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/structural_roles#structural_roles_with_html_equivalents" >blockquote</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>Any</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLQuoteElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("q")}} element for inline quotations. - The {{HTMLElement("cite")}} element for source citations.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/nav/index.md
--- title: "<nav>: The Navigation Section element" slug: Web/HTML/Element/nav page-type: html-element browser-compat: html.elements.nav --- {{HTMLSidebar}} The **`<nav>`** [HTML](/en-US/docs/Web/HTML) element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes. {{EmbedInteractiveExample("pages/tabbed/nav.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - It's not necessary for all links to be contained in a `<nav>` element. `<nav>` is intended only for a major block of navigation links; typically the {{HTMLElement("footer")}} element often has a list of links that don't need to be in a {{HTMLElement("nav")}} element. - A document may have several {{HTMLElement("nav")}} elements, for example, one for site navigation and one for intra-page navigation. [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) can be used in such case to promote accessibility, see [example](/en-US/docs/Web/HTML/Element/Heading_Elements#labeling_section_content). - User agents, such as screen readers targeting disabled users, can use this element to determine whether to omit the initial rendering of navigation-only content. ## Examples In this example, a `<nav>` block is used to contain an unordered list ({{HTMLElement("ul")}}) of links. With appropriate CSS, this can be presented as a sidebar, navigation bar, or drop-down menu. ```html <nav class="menu"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> ``` The semantics of the `nav` element is that of providing links. However a `nav` element doesn't have to contain a list, it can contain other kinds of content as well. In this navigation block, links are provided in prose: ```html <nav> <h2>Navigation</h2> <p> You are on my home page. To the north lies <a href="/blog">my blog</a>, from whence the sounds of battle can be heard. To the east you can see a large mountain, upon which many <a href="/school">school papers</a> are littered. Far up this mountain you can spy a little figure who appears to be me, desperately scribbling a <a href="/school/thesis">thesis</a>. </p> <p> To the west are several exits. One fun-looking exit is labeled <a href="https://games.example.com/">"games"</a>. Another more boring-looking exit is labeled <a href="https://isp.example.net/">ISP™</a>. </p> <p> To the south lies a dark and dank <a href="/about">contacts page</a>. Cobwebs cover its disused entrance, and at one point you see a rat run quickly out of the page. </p> </nav> ``` ### 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#sectioning_content" >sectioning 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 >. </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/Navigation_Role" >navigation</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("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Other 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("hgroup")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("address")}}; - [Sections and outlines of an HTML document](/en-US/docs/Web/HTML/Element/Heading_Elements). - [ARIA: Navigation role](/en-US/docs/Web/Accessibility/ARIA/Roles/navigation_role)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/map/index.md
--- title: "<map>: The Image Map element" slug: Web/HTML/Element/map page-type: html-element browser-compat: html.elements.map --- {{HTMLSidebar}} The **`<map>`** [HTML](/en-US/docs/Web/HTML) element is used with {{HTMLElement("area")}} elements to define an image map (a clickable link area). {{EmbedInteractiveExample("pages/tabbed/map.html", "tabbed-standard")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `name` - : The `name` attribute gives the map a name so that it can be referenced. The attribute must be present and must have a non-empty value with no space characters. The value of the `name` attribute must not be equal to the value of the `name` attribute of another `<map>` element in the same document. If the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute is also specified, both attributes must have the same value. ## Examples ### Image map with two areas Click the left-hand parrot for JavaScript, or the right-hand parrot for CSS. #### HTML ```html <!-- Photo by Juliana e Mariana Amorim on Unsplash --> <map name="primary"> <area shape="circle" coords="75,75,75" href="https://developer.mozilla.org/docs/Web/JavaScript" target="_blank" alt="JavaScript" /> <area shape="circle" coords="275,75,75" href="https://developer.mozilla.org/docs/Web/CSS" target="_blank" alt="CSS" /> </map> <img usemap="#primary" src="parrots.jpg" alt="350 x 150 picture of two parrots" /> ``` #### Result {{ EmbedLiveSample('Image map with two areas', '', '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#phrasing_content" >phrasing content</a >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Any <a href="/en-US/docs/Web/HTML/Content_categories#transparent_content_model" >transparent</a > 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#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("HTMLMapElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("a")}} - {{HTMLElement("area")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/button/index.md
--- title: "<button>: The Button element" slug: Web/HTML/Element/button page-type: html-element browser-compat: html.elements.button --- {{HTMLSidebar}} The **`<button>`** [HTML](/en-US/docs/Web/HTML) element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs an action, such as submitting a [form](/en-US/docs/Learn/Forms) or opening a dialog. By default, HTML buttons are presented in a style resembling the platform the {{Glossary("user agent")}} runs on, but you can change buttons' appearance with [CSS](/en-US/docs/Web/CSS). {{EmbedInteractiveExample("pages/tabbed/button.html", "tabbed-shorter")}} ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `autofocus` - : This Boolean attribute specifies that the button should have input [focus](/en-US/docs/Web/API/HTMLElement/focus) when the page loads. **Only one element in a document can have this attribute.** - `disabled` - : This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or focused. Firefox, unlike other browsers, [persists 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. To control this feature, use the [`autocomplete`](#autocomplete) attribute. - `form` - : The {{HTMLElement("form")}} element to associate the button with (its _form owner_). The value of this attribute must be the `id` of a `<form>` in the same document. (If this attribute is not set, the `<button>` is associated with its ancestor `<form>` element, if any.) This attribute lets you associate `<button>` elements to `<form>`s anywhere in the document, not just inside a `<form>`. It can also override an ancestor `<form>` element. - `formaction` - : The URL that processes the information submitted by the button. Overrides the [`action`](/en-US/docs/Web/HTML/Element/form#action) attribute of the button's form owner. Does nothing if there is no form owner. - `formenctype` - : If the button is a submit button (it's inside/associated with a `<form>` and doesn't have `type="button"`), specifies how to encode the form data that is submitted. Possible values: - `application/x-www-form-urlencoded`: The default if the attribute is not used. - `multipart/form-data`: Used to submit {{HTMLElement("input")}} elements with their [`type`](/en-US/docs/Web/HTML/Element/input#type) attributes set to `file`. - `text/plain`: Specified as a debugging aid; shouldn't be used for real form submission. If this attribute is specified, it overrides the [`enctype`](/en-US/docs/Web/HTML/Element/form#enctype) attribute of the button's form owner. - `formmethod` - : If the button is a submit button (it's inside/associated with a `<form>` and doesn't have `type="button"`), this attribute specifies the [HTTP method](/en-US/docs/Web/HTTP/Methods) used to submit the form. Possible values: - `post`: The data from the form are included in the body of the HTTP request when sent to the server. Use when the form contains information that shouldn't be public, like login credentials. - `get`: The form data are appended to the form's `action` URL, with a `?` as a separator, and the resulting URL is sent to the server. Use this method when the form [has no side effects](/en-US/docs/Glossary/Idempotent), like search forms. - `dialog`: This method is used to indicate that the button closes the [dialog](/en-US/docs/Web/HTML/Element/dialog) with which it is associated, and does not transmit the form data at all. If specified, this attribute overrides the [`method`](/en-US/docs/Web/HTML/Element/form#method) attribute of the button's form owner. - `formnovalidate` - : If the button is a submit button, this Boolean attribute specifies that the form is not to be [validated](/en-US/docs/Learn/Forms/Form_validation) when it is submitted. If this attribute is specified, it overrides the [`novalidate`](/en-US/docs/Web/HTML/Element/form#novalidate) attribute of the button's form owner. This attribute is also available on [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) and [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit) elements. - `formtarget` - : If the button is a submit button, this attribute is an author-defined name or standardized, underscore-prefixed keyword indicating where to display the response from submitting the form. This is the `name` of, or keyword for, a _browsing context_ (a tab, window, or {{HTMLElement("iframe")}}). If this attribute is specified, it overrides the [`target`](/en-US/docs/Web/HTML/Element/form#target) attribute of the button's form owner. The following keywords have special meanings: - `_self`: Load the response into the same browsing context as the current one. This is the default if the attribute is not specified. - `_blank`: Load the response into a new unnamed browsing context — usually a new tab or window, depending on the user's browser settings. - `_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 way as `_self`. - `name` - : The name of the button, submitted as a pair with the button's `value` as part of the form data, when that button is used to submit the form. - `popovertarget` - : Turns a `<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 `<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. - `type` - : The default behavior of the button. Possible values are: - `submit`: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a `<form>`, or if the attribute is an empty or invalid value. - `reset`: The button resets all the controls to their initial values, like [\<input type="reset">](/en-US/docs/Web/HTML/Element/input/reset). (This behavior tends to annoy users.) - `button`: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element's events, which are triggered when the events occur. - `value` - : Defines the value associated with the button's `name` when it's submitted with the form data. This value is passed to the server in params when the form is submitted using this button. ## Notes A submit button with the attribute `formaction` set, but without an associated form does nothing. You have to set a form owner, either by wrapping it in a `<form>` or set the attribute `form` to the id of the form. `<button>` elements are much easier to style than {{HTMLElement("input")}} elements. You can add inner HTML content (think `<i>`, `<br>`, or even `<img>`), and use {{Cssxref("::after")}} and {{Cssxref("::before")}} pseudo-elements for complex rendering. If your buttons are not for submitting form data to a server, be sure to set their `type` attribute to `button`. Otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document. While `<button type="button">` has no default behavior, event handlers can be scripted to trigger behaviors. An activated button can perform programmable actions using [JavaScript](/en-US/docs/Learn/JavaScript), such as removing an item from a list. ## Examples ```html <button name="button">Press me</button> ``` {{ EmbedLiveSample('Example', 200, 64) }} ## Accessibility concerns ### Icon buttons Buttons that only show an icon to represent do not have an _accessible name_. Accessible names provide information for assistive technology, such as screen readers, to access when they parse the document and generate [an accessibility tree](/en-US/docs/Learn/Accessibility/What_is_accessibility#accessibility_apis). Assistive technology then uses the accessibility tree to navigate and manipulate page content. To give an icon button an accessible name, put text in the `<button>` element that concisely describes the button's functionality. #### Examples ```html <button name="favorite"> <svg aria-hidden="true" viewBox="0 0 10 10"> <path d="M7 9L5 8 3 9V6L1 4h3l1-3 1 3h3L7 6z" /> </svg> Add to favorites </button> ``` ##### Result {{EmbedLiveSample('Icon buttons')}} If you want to visually hide the button's text, an accessible way to do so is to use [a combination of CSS properties](https://gomakethings.com/hidden-content-for-better-a11y/#hiding-the-link) to remove it visually from the screen, but keep it parsable by assistive technology. However, it is worth noting that leaving the button text visually apparent can aid people who may not be familiar with the icon's meaning or understand the button's purpose. This is especially relevant for people who are not technologically sophisticated, or who may have different cultural interpretations for the icon the button uses. - [What is an accessible name? | The Paciello Group](https://www.tpgi.com/what-is-an-accessible-name/) - [MDN Understanding WCAG, Guideline 4.1 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Robust#guideline_4.1_—_compatible_maximize_compatibility_with_current_and_future_user_agents_including_assistive_technologies) - [Understanding Success Criterion 4.1.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/ensure-compat-rsv.html) ### Size and Proximity #### Size Interactive elements such as buttons 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/) #### Proximity Large amounts of interactive content — including buttons — placed in close visual proximity to each other should have space separating them. This spacing is beneficial for people who are experiencing motor control issues, who may accidentally activate the wrong interactive content. Spacing may be created using CSS properties such as {{cssxref("margin")}}. - [Hand tremors and the giant-button-problem - Axess Lab](https://axesslab.com/hand-tremors/) ### ARIA state information To describe the state of a button the correct ARIA attribute to use is [`aria-pressed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) and not [`aria-checked`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) or [`aria-selected`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected). To find out more read the information about the [ARIA button role](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role). ### Firefox Firefox will add a small dotted border on a focused button. This border is declared through CSS in the browser stylesheet, but you can override it to add your own focused style using [`button::-moz-focus-inner { }`](/en-US/docs/Web/CSS/::-moz-focus-inner). If overridden, it is important to **ensure that the state change when focus is moved to the button is high enough** that people experiencing low vision conditions will be able to perceive it. Color contrast ratio is determined by comparing the luminosity of the button text and background color values compared to the background the button is placed on. In order to meet current [Web Content Accessibility Guidelines (WCAG)](https://www.w3.org/WAI/standards-guidelines/wcag/), a ratio of 4.5:1 is required for text content and 3:1 for large text. (Large text is defined as 18.66px and {{cssxref("font-weight", "bold")}} or larger, or 24px or larger.) - [WebAIM: Color Contrast Checker](https://webaim.org/resources/contrastchecker/) - [MDN Understanding WCAG, Guideline 1.4 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.4_make_it_easier_for_users_to_see_and_hear_content_including_separating_foreground_from_background) - [Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html) ### Clicking and focus Whether clicking on a {{HTMLElement("button")}} or {{HTMLElement("input")}} button types causes it to (by default) become focused varies by browser and OS. Most browsers do give focus to a button being clicked, but [Safari does not, by design](https://webkit.org/b/22261). ## 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 >, 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_content" >form-associated</a > element, 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 <a href="/en-US/docs/Web/HTML/Content_categories#interactive_content" >Interactive 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/button_role" >button</a ></code > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <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> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLButtonElement")}}</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/heading_elements/index.md
--- title: "<h1>–<h6>: The HTML Section Heading elements" slug: Web/HTML/Element/Heading_Elements page-type: html-element browser-compat: html.elements.h1 --- {{HTMLSidebar}} The **`<h1>`** to **`<h6>`** [HTML](/en-US/docs/Web/HTML) elements represent six levels of section headings. `<h1>` is the highest section level and `<h6>` is the lowest. By default, all heading elements create a [block-level](/en-US/docs/Glossary/Block-level_content) box in the layout, starting on a new line and taking up the full width available in their containing block. {{EmbedInteractiveExample("pages/tabbed/h1-h6.html", "tabbed-standard")}} ## Attributes These elements only include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Heading information can be used by user agents to construct a table of contents for a document automatically. - Do not use heading elements to resize text. Instead, use the {{glossary("CSS")}} {{cssxref("font-size")}} property. - Do not skip heading levels: always start from `<h1>`, followed by `<h2>` and so on. ### Avoid using multiple `<h1>` elements on one page While using multiple `<h1>` elements on one page is allowed by the HTML standard (as long as they are not [nested](#nesting)), this is not considered a best practice. A page should generally have a single `<h1>` element that describes the content of the page (similar to the document's [`<title> element`](/en-US/docs/Web/HTML/Element/title)). > **Note:** Nesting multiple `<h1>` elements in nested [sectioning elements](/en-US/docs/Web/HTML/Element#content_sectioning) was allowed in older versions of the HTML standard. However, this was never considered a best practice and is now non-conforming. Read more in [There Is No Document Outline Algorithm](https://adrianroselli.com/2016/08/there-is-no-document-outline-algorithm.html). Prefer using only one `<h1>` per page and [nest headings](#nesting) without skipping levels. ## Examples ### All headings The following code shows all the heading levels, in use. ```html <h1>Heading level 1</h1> <h2>Heading level 2</h2> <h3>Heading level 3</h3> <h4>Heading level 4</h4> <h5>Heading level 5</h5> <h6>Heading level 6</h6> ``` {{EmbedLiveSample('All_headings', '280', '300')}} ### Example page The following code shows a few headings with some content under them. ```html <h1>Heading elements</h1> <h2>Summary</h2> <p>Some text here…</p> <h2>Examples</h2> <h3>Example 1</h3> <p>Some text here…</p> <h3>Example 2</h3> <p>Some text here…</p> <h2>See also</h2> <p>Some text here…</p> ``` {{EmbedLiveSample('Example_page', '280', '480')}} ## Accessibility concerns ### Navigation A common navigation technique for users of screen reading software is to quickly jump from heading to heading in order to determine the content of the page. Because of this, it is important to not skip one or more heading levels. Doing so may create confusion, as the person navigating this way may be left wondering where the missing heading is. **Don't do this:** ```html example-bad <h1>Heading level 1</h1> <h3>Heading level 3</h3> <h4>Heading level 4</h4> ``` **Prefer this:** ```html example-good <h1>Heading level 1</h1> <h2>Heading level 2</h2> <h3>Heading level 3</h3> ``` #### Nesting Headings may be nested as subsections to reflect the organization of the content of the page. Most screen readers can also generate an ordered list of all the headings on a page, which can help a person quickly determine the hierarchy of the content: 1. `h1` Beetles 1. `h2` Etymology 2. `h2` Distribution and Diversity 3. `h2` Evolution 1. `h3` Late Paleozoic 2. `h3` Jurassic 3. `h3` Cretaceous 4. `h3` Cenozoic 4. `h2` External Morphology 1. `h3` Head 1. `h4` Mouthparts 2. `h3` Thorax 1. `h4` Prothorax 2. `h4` Pterothorax 3. `h3` Legs 4. `h3` Wings 5. `h3` Abdomen When headings are nested, heading levels may be "skipped" when closing a subsection. - [Headings • Page Structure • WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/page-structure/headings/) - [MDN Understanding WCAG, Guideline 1.3 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable#guideline_1.3_—_create_content_that_can_be_presented_in_different_ways) - [Understanding Success Criterion 1.3.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/content-structure-separation-programmatic.html) - [MDN Understanding WCAG, Guideline 2.4 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_—_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are) - [Understanding Success Criterion 2.4.1 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-skip.html) - [Understanding Success Criterion 2.4.6 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-descriptive.html) - [Understanding Success Criterion 2.4.10 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-headings.html) ### Labeling section content Another common navigation technique for users of screen reading software is to generate a list of [sectioning content](/en-US/docs/Web/HTML/Element#content_sectioning) and use it to determine the page's layout. Sectioning content can be labeled using a combination of the [`aria-labelledby`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) and [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attributes, with the label concisely describing the purpose of the section. This technique is useful for situations where there is more than one sectioning element on the same page. #### Sectioning content examples ```html <header> <nav aria-labelledby="primary-navigation"> <h2 id="primary-navigation">Primary navigation</h2> <!-- navigation items --> </nav> </header> <!-- page content --> <footer> <nav aria-labelledby="footer-navigation"> <h2 id="footer-navigation">Footer navigation</h2> <!-- navigation items --> </nav> </footer> ``` {{EmbedLiveSample('Sectioning_content_examples')}} In this example, screen reading technology would announce that there are two {{HTMLElement("nav")}} sections, one called "Primary navigation" and one called "Footer navigation". If labels were not provided, the person using screen reading software may have to investigate each `nav` element's contents to determine their purpose. - [Using the aria-labelledby attribute](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby) - [Labeling Regions • Page Structure • W3C WAI Web Accessibility Tutorials](https://www.w3.org/WAI/tutorials/page-structure/labels/#using-aria-labelledby) ## 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> <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> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/heading_role" >heading</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role"><code>tab</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("HTMLHeadingElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("p")}} - {{HTMLElement("div")}} - {{HTMLElement("section")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/caption/index.md
--- title: "<caption>: The Table Caption element" slug: Web/HTML/Element/caption page-type: html-element browser-compat: html.elements.caption --- {{HTMLSidebar}} The **`<caption>`** [HTML](/en-US/docs/Web/HTML) element specifies the caption (or title) of a table, providing the table an {{glossary("accessible description")}}. {{EmbedInteractiveExample("pages/tabbed/caption.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 on which side of the table the caption should be displayed. The possible {{Glossary("enumerated", "enumerated")}} values are `left`, `top`, `right`, or `bottom`. Use the {{cssxref("caption-side")}} and {{cssxref("text-align")}} CSS properties instead, as this attribute is deprecated. ## Usage notes - If included, the `<caption>` element must be the first child of its parent {{htmlelement("table")}} element. - When a `<table>` is nested within a {{HTMLElement("figure")}} as the figure's only content, it should be captioned via a {{HTMLElement("figcaption")}} for the `<figure>` instead of as a `<caption>` nested within the `<table>`. - Any {{cssxref("background-color")}} applied to a table will not be applied to its caption. Add a `background-color` to the `<caption>` element as well if you want the same color to be behind both. ## Example See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. This example demonstrates a basic table that includes a caption describing the data presented. Such a "title" is helpful for users who are quickly scanning the page, and it is especially beneficial for visually impaired users, allowing them to determine the table's relevance quickly without the need to have a screen reader read the contents of many cells just to find out what the table is about. #### HTML A `<caption>` element is used as the first child of the {{HTMLElement("table")}}, with text content similar to a title to describe the table data. Three rows, the first being a header row, with two columns are created using the {{HTMLElement("tr")}}, {{HTMLElement("th")}} and {{HTMLElement("td")}} elements after the `<caption>`. ```html <table> <caption> User login email addresses </caption> <tr> <th>Login</th> <th>Email</th> </tr> <tr> <td>user1</td> <td>[email protected]</td> </tr> <tr> <td>user2</td> <td>[email protected]</td> </tr> </table> ``` #### CSS Some basic CSS is used to align and highlight the `<caption>`. ```css caption { caption-side: top; text-align: left; padding-bottom: 10px; font-weight: bold; } ``` ```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 { background-color: rgb(230 230 230); } td { text-align: center; } ``` #### Result {{EmbedLiveSample('Example', 650, 140)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >Flow content</a >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The end tag can be omitted if the element is not immediately followed by ASCII whitespace or a comment. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("table")}} element, as its first descendant. </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">caption</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("HTMLTableCaptionElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Learn: HTML tables](/en-US/docs/Learn/HTML/Tables) - {{HTMLElement("col")}}, {{HTMLElement("colgroup")}}, {{HTMLElement("table")}}, {{HTMLElement("tbody")}}, {{HTMLElement("td")}}, {{HTMLElement("tfoot")}}, {{HTMLElement("th")}}, {{HTMLElement("thead")}}, {{HTMLElement("tr")}}: Other table-related elements - {{cssxref("caption-side")}}: CSS property to position the `<caption>` relative to its parent {{HTMLElement("table")}} - {{cssxref("text-align")}}: CSS property to horizontally align the text content of the `<caption>`
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/title/index.md
--- title: "<title>: The Document Title element" slug: Web/HTML/Element/title page-type: html-element browser-compat: html.elements.title --- {{HTMLSidebar}} The **`<title>`** [HTML](/en-US/docs/Web/HTML) element defines the document's title that is shown in a {{glossary("Browser", "browser")}}'s title bar or a page's tab. It only contains text; tags within the element are ignored. ```html <title>Grandma's Heavy Metal Festival Journal</title> ``` ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The `<title>` element is always used within a page's {{HTMLElement("head")}} block. ### Page titles and SEO The contents of a page title can have significant implications for search engine optimization ({{glossary("SEO")}}). In general, a longer, descriptive title performs better than short or generic titles. The content of the title is one of the components used by search engine algorithms to decide the order in which to list pages in search results. Also, the title is the initial "hook" by which you grab the attention of readers glancing at the search results page. A few guidelines and tips for composing good titles: - Avoid one- or two-word titles. Use a descriptive phrase, or a term-definition pairing for glossary or reference-style pages. - Search engines typically display about the first 55–60 characters of a page title. Text beyond that may be lost, so try not to have titles longer than that. If you must use a longer title, make sure the important parts come earlier and that nothing critical is in the part of the title that is likely to be dropped. - Don't use "keyword blobs." If your title is just a list of words, algorithms often reduce your page's position in the search results. - Try to make sure your titles are as unique as possible within your own site. Duplicate—or near-duplicate—titles can contribute to inaccurate search results. ## Examples ```html <title>Awesome interesting stuff</title> ``` This example establishes a page whose title (as displayed at the top of the window or in the window's tab) as "Awesome interesting stuff". ## Accessibility concerns It is important to provide an accurate and concise title to describe the page's purpose. A common navigation technique for users of assistive technology is to read the page title and infer the content the page contains. This is because navigating into a page to determine its content can be a time-consuming and potentially confusing process. Titles should be unique to every page of a website, ideally surfacing the primary purpose of the page first, followed by the name of the website. Following this pattern will help ensure that the primary purpose of the page is announced by a screen reader first. This provides a far better experience than having to listen to the name of a website before the unique page title, for every page a user navigates to in the same website. ### Examples ```html <title>Menu - Blue House Chinese Food - FoodYum: Online takeout today!</title> ``` If a form submission contains errors and the submission re-renders the current page, the title can be used to help make users aware of any errors with their submission. For instance, update the page `title` value to reflect significant page state changes (such as form validation problems). ```html <title> 2 errors - Your order - Sea Food Store - Food: Online takeout today! </title> ``` > **Note:** Presently, dynamically updating a page's title will not be automatically announced by screen readers. If you are going to update the page title to reflect significant changes to a page's state, then the use of [ARIA Live Regions](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) may be necessary, as well. - [MDN Understanding WCAG, Guideline 2.4 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_—_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are) - [Understanding Success Criterion 2.4.2 | W3C Understanding WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/page-titled.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#metadata_content" >Metadata content</a >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> Text that is not inter-element {{glossary("whitespace")}}. </td> </tr> <tr> <th scope="row">Tag omission</th> <td> Both opening and closing tags are required. Note that leaving off <code>&#x3C;/title></code> should cause the browser to ignore the rest of the page. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{ HTMLElement("head") }} element that contains no other {{ HTMLElement("title") }} 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("HTMLTitleElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - SVG [`<title>`](/en-US/docs/Web/SVG/Element/title) element
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/tt/index.md
--- title: "<tt>: The Teletype Text element" slug: Web/HTML/Element/tt page-type: html-element status: - deprecated browser-compat: html.elements.tt --- {{HTMLSidebar}}{{deprecated_header}} The **`<tt>`** [HTML](/en-US/docs/Web/HTML) element creates inline text which is presented using the {{Glossary("user agent", "user agent's")}} default monospace font face. This element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer. The terms **non-proportional**, **monotype**, and **monospace** are used interchangeably and have the same general meaning: they describe a typeface whose characters are all the same number of pixels wide. This element is obsolete, however. You should use the more semantically helpful {{HTMLElement("code")}}, {{HTMLElement("kbd")}}, {{HTMLElement("samp")}}, or {{HTMLElement("var")}} elements for inline text that needs to be presented in monospace type, or the {{HTMLElement("pre")}} tag for content that should be presented as a separate block. > **Note:** If none of the semantic elements are appropriate for your use case (for example, if you need to show some content in a non-proportional font), you should consider using the {{ HTMLElement("span") }} element, styling it as desired using CSS. The {{cssxref("font-family")}} property is a good place to start. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes) ## Examples ### Basic example This example uses `<tt>` to show text entered into, and output by, a terminal application. ```html <p> Enter the following at the telnet command prompt: <code>set localecho</code><br /> The telnet client should display: <tt>Local Echo is on</tt> </p> ``` #### Result {{EmbedLiveSample("Basic_example", 650, 80)}} ### Overriding the default font You can override the browser's default font—if the browser permits you to do so, which it isn't required to do—using CSS: #### CSS ```css tt { font-family: "Lucida Console", "Menlo", "Monaco", "Courier", monospace; } ``` #### HTML ```html <p> Enter the following at the telnet command prompt: <code>set localecho</code><br /> The telnet client should display: <tt>Local Echo is on</tt> </p> ``` #### Result {{EmbedLiveSample("Overriding_the_default_font", 650, 80)}} ## Usage notes The `<tt>` element is, by default, rendered using the browser's default non-proportional font. You can override this using CSS by creating a rule using the `tt` selector, as seen in the example [Overriding the default font](#overriding_the_default_font) above. > **Note:** User-configured changes to the default monospace font setting may take precedence over your CSS. Although this element wasn't officially deprecated in HTML 4.01, its use was discouraged in favor of the semantic elements and/or CSS. The `<tt>` element is obsolete in HTML 5. ## 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">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 semantic {{HTMLElement("code")}}, {{HTMLElement("var")}}, {{HTMLElement("kbd")}}, and {{HTMLElement("samp")}} elements - The {{HTMLElement("pre")}} element for displaying preformatted text blocks
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/main/index.md
--- title: "<main>: The Main element" slug: Web/HTML/Element/main page-type: html-element browser-compat: html.elements.main --- {{HTMLSidebar}} The **`<main>`** [HTML](/en-US/docs/Web/HTML) element represents the dominant content of the {{HTMLElement("body")}} of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. {{EmbedInteractiveExample("pages/tabbed/main.html","tabbed-shorter")}} A document mustn't have more than one `<main>` element that doesn't have the [`hidden`](/en-US/docs/Web/HTML/Global_attributes#hidden) attribute specified. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes The content of a `<main>` element should be unique to the document. Content that is repeated across a set of documents or document sections such as sidebars, navigation links, copyright information, site logos, and search forms shouldn't be included unless the search form is the main function of the page. `<main>` doesn't contribute to the document's outline; that is, unlike elements such as {{HTMLElement("body")}}, headings such as {{HTMLElement("Heading_Elements", "h2")}}, and such, `<main>` doesn't affect the {{glossary("DOM", "DOM's")}} concept of the structure of the page. It's strictly informative. ## Examples ```html <!-- other content --> <main> <h1>Apples</h1> <p>The apple is the pomaceous fruit of the apple tree.</p> <article> <h2>Red Delicious</h2> <p> These bright red apples are the most common found in many supermarkets. </p> <p>…</p> <p>…</p> </article> <article> <h2>Granny Smith</h2> <p>These juicy, green apples make a great filling for apple pies.</p> <p>…</p> <p>…</p> </article> </main> <!-- other content --> ``` ### Result {{EmbedLiveSample('Examples')}} ## Accessibility concerns ### Landmark The `<main>` element behaves like a [`main` landmark](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role) role. [Landmarks](/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques#landmark_roles) can be used by assistive technology to quickly identify and navigate to large sections of the document. Prefer using the `<main>` element over declaring `role="main"`, unless there are [legacy browser support concerns](#browser_compatibility). ### Skip navigation Skip navigation, also known as "skipnav", is a technique that allows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). This lets the user access the main content of the page faster. Adding an [`id`](/en-US/docs/Web/HTML/Global_attributes#id) attribute to the `<main>` element lets it be a target of a skip navigation link. ```html <body> <a href="#main-content">Skip to main content</a> <!-- navigation and header content --> <main id="main-content"> <!-- main page content --> </main> </body> ``` - [WebAIM: "Skip Navigation" Links](https://webaim.org/techniques/skipnav/) ### Reader mode Browser reader mode functionality looks for the presence of the `<main>` element, as well as [heading](/en-US/docs/Web/HTML/Element/Heading_Elements) and [content sectioning elements](/en-US/docs/Web/HTML/Element#content_sectioning) when converting content into a specialized reader view. - [Building websites for Safari Reader Mode and other reading apps.](https://medium.com/@mandy.michael/building-websites-for-safari-reader-mode-and-other-reading-apps-1562913c86c9) ## 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 >. </td> </tr> <tr> <th scope="row">Tag omission</th> <td>None; both the starting and ending tags are mandatory.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> Where <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a > is expected, but only if it is a <a href="https://html.spec.whatwg.org/multipage/grouping-content.html#hierarchically-correct-main-element" >hierarchically correct <code>main</code> element</a >. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <code ><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Main_role" >main</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("HTMLElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Basic structural elements: {{HTMLElement("html")}}, {{HTMLElement("head")}}, {{HTMLElement("body")}} - Section-related elements: {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("footer")}}, {{HTMLElement("header")}}, or {{HTMLElement("nav")}} - [ARIA: Main role](/en-US/docs/Web/Accessibility/ARIA/Roles/main_role)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/frameset/index.md
--- title: <frameset> slug: Web/HTML/Element/frameset page-type: html-element status: - deprecated browser-compat: html.elements.frameset --- {{HTMLSidebar}}{{Deprecated_header}} The **`<frameset>`** [HTML](/en-US/docs/Web/HTML) element is used to contain {{HTMLElement("frame")}} elements. > **Note:** Because the use of frames is now discouraged in favor of using {{HTMLElement("iframe")}}, this element is not typically used by modern websites. ## Attributes Like all other HTML elements, this element supports the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `cols` {{Deprecated_Inline}} - : This attribute specifies the number and size of horizontal spaces in a frameset. - `rows` {{Deprecated_Inline}} - : This attribute specifies the number and size of vertical spaces in a frameset. ## Example ### A frameset document A frameset document has a `<frameset>` element instead of a {{HTMLElement("body")}} element. The {{HTMLElement("frame")}} elements are placed within the `<frameset>`. ```html <!doctype html> <html lang="en-US"> <head> <!-- Document metadata goes here --> </head> <frameset cols="50%, 50%"> <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("frame")}} - {{HTMLElement("iframe")}}
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/noscript/index.md
--- title: "<noscript>: The Noscript element" slug: Web/HTML/Element/noscript page-type: html-element browser-compat: html.elements.noscript --- {{HTMLSidebar}} The **`<noscript>`** [HTML](/en-US/docs/Web/HTML) element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Examples ```html <noscript> <!-- anchor linking to external file --> <a href="https://www.mozilla.org/">External Link</a> </noscript> <p>Rocks!</p> ``` ### Result with scripting enabled Rocks! ### Result with scripting disabled [External Link](https://www.mozilla.org/) Rocks! ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#metadata_content" >Metadata content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#flow_content" >flow content</a >, <a href="/en-US/docs/Web/HTML/Content_categories#phrasing_content" >phrasing content</a >. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> When scripting is disabled and when it is a descendant of the {{HTMLElement("head")}} element: in any order, zero or more {{HTMLElement("link")}} elements, zero or more {{HTMLElement("style")}} elements, and zero or more {{HTMLElement("meta")}} elements.<br />When scripting is disabled and when it isn't a descendant of the {{HTMLElement("head")}} element: any <a href="/en-US/docs/Web/HTML/Content_categories#transparent_content_model" >transparent content</a >, but no <code>&#x3C;noscript></code> element must be among its descendants.<br />Otherwise: flow content or phrasing 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#phrasing_content" >phrasing content</a >, if there are no ancestor <code>&#x3C;noscript></code> element, or in a {{HTMLElement("head")}} element (but only for an HTML document), here again if there are no ancestor <code>&#x3C;noscript></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("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/menuitem/index.md
--- title: <menuitem> slug: Web/HTML/Element/menuitem page-type: html-element status: - deprecated - non-standard --- {{HTMLSidebar}}{{Deprecated_Header}}{{Non-standard_header}} The **`<menuitem>`** [HTML](/en-US/docs/Web/HTML) element represents a command that a user is able to invoke through a popup menu. This includes context menus, as well as menus that might be attached to a menu button. A command can either be defined explicitly, with a textual label and optional icon to describe its appearance, or alternatively as an _indirect command_ whose behavior is defined by a separate element. Commands can also optionally include a checkbox or be grouped to share radio buttons. (Menu items for indirect commands gain checkboxes or radio buttons when defined against elements `<input type="checkbox">` and `<input type="radio">`.) ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes); in particular `title` can be used to describe the command, or provide usage hints. - `checked` {{Deprecated_Inline}} {{Non-standard_Inline}} - : Boolean attribute which indicates whether the command is selected. May only be used when the `type` attribute is `checkbox` or `radio`. - `command` {{Deprecated_Inline}} {{Non-standard_Inline}} - : Specifies the ID of a separate element, indicating a command to be invoked indirectly. May not be used within a menu item that also includes the attributes `checked`, `disabled`, `icon`, `label`, `radiogroup` or `type`. - `default` {{Deprecated_Inline}} {{Non-standard_Inline}} - : This Boolean attribute indicates use of the same command as the menu's subject element (such as a `button` or `input`). - `disabled` {{Deprecated_Inline}} {{Non-standard_Inline}} - : Boolean attribute which indicates that the command is not available in the current state. Note that `disabled` is distinct from `hidden`; the `disabled` attribute is appropriate in any context where a change in circumstances might render the command relevant. - `icon` {{Deprecated_Inline}} {{Non-standard_Inline}} - : Image URL, used to provide a picture to represent the command. - `label` - : The name of the command as shown to the user. Required when a `command` attribute is not present. - `radiogroup` {{Deprecated_Inline}} {{Non-standard_Inline}} - : This attribute specifies the name of a group of commands to be toggled as radio buttons when selected. May only be used where the `type` attribute is `radio`. - `type` {{Deprecated_Inline}} {{Non-standard_Inline}} - : This attribute indicates the kind of command, and can be one of three values. - `command`: A regular command with an associated action. This is the missing value default. - `checkbox`: Represents a command that can be toggled between two different states. - `radio`: Represent one selection from a group of commands that can be toggled as radio buttons. ## Examples ### HTML ```html <!-- A <div> element with a context menu --> <div contextmenu="popup-menu">Right-click to see the adjusted context menu</div> <menu type="context" id="popup-menu"> <menuitem type="checkbox" checked>Checkbox</menuitem> <hr /> <menuitem type="command" label="This command does nothing" icon="favicon-192x192.png"> Commands don't render their contents. </menuitem> <menuitem type="command" label="This command has javascript" onclick="alert('command clicked')"> Commands don't render their contents. </menuitem> <hr /> <menuitem type="radio" radiogroup="group1">Radio Button 1</menuitem> <menuitem type="radio" radiogroup="group1">Radio Button 2</menuitem> </menu> ``` ### CSS ```css div { width: 300px; height: 80px; background-color: lightgreen; } ``` ### Result {{EmbedLiveSample("Example", '100%', 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>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>Must have a start tag and must not have an end tag.</td> </tr> <tr> <th scope="row">Permitted parents</th> <td> The {{HTMLElement("menu")}} element, where that element is in the <em>popup menu</em> state. (If specified, the <code>type</code> attribute of the {{HTMLElement("menu")}} element must be <code>popup</code>; if missing, the parent element of the {{HTMLElement("menu")}} must itself be a {{HTMLElement("menu")}} in the <em>popup menu</em> state.) </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>None</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLMenuItemElement")}}</td> </tr> </tbody> </table> ## Specifications Not part of any current specifications. ## Browser compatibility No longer supported in any browser. Firefox, the only browser that supported this element, removed support in 85. ## See also - [HTML context menus in Firefox (Screencast and Code)](https://hacks.mozilla.org/2011/11/html5-context-menus-in-firefox-screencast-and-code/)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/colgroup/index.md
--- title: "<colgroup>: The Table Column Group element" slug: Web/HTML/Element/colgroup page-type: html-element browser-compat: html.elements.colgroup --- {{HTMLSidebar}} The **`<colgroup>`** [HTML](/en-US/docs/Web/HTML) element defines a group of columns within a table. {{EmbedInteractiveExample("pages/tabbed/colgroup.html","tabbed-taller")}} ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `span` - : Specifies the number of consecutive columns the `<colgroup>` element spans. The value must be a positive integer greater than zero. If not present, its default value is `1`. > **Note:** The `span` attribute is not permitted if there are one or more {{HTMLElement("col")}} elements within the `<colgroup>`. ### Deprecated attributes The following attributes are deprecated and should not be used. They are documented below for reference when updating existing code and for historical interest only. - `align` {{deprecated_inline}} - : Specifies the horizontal alignment of each column group 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. Note that the descendant {{HTMLElement("col")}} elements may override this value using their own [`align`](/en-US/docs/Web/HTML/Element/col#align) attribute. Use the {{cssxref("text-align")}} CSS property on the {{htmlelement("td")}} and {{htmlelement("th")}} elements instead, as this attribute is deprecated. > **Note:** Setting `text-align` on the `<colgroup>` element has no effect as {{HTMLElement("td")}} and {{HTMLElement("th")}} elements are not descendants of the `<colgroup>` element, and therefore they do not inherit from it. > > If the table does not use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, use the `td:nth-of-type(an+b)` CSS selector per column, where `a` is the total number of the columns in the table and `b` is the ordinal position of the column in the table, e.g. `td:nth-of-type(7n+2) { text-align: right; }` to right-align the second column cells. > > If the table does use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial. - `bgcolor` {{deprecated_inline}} - : Defines the background color of each column group cell. The value is an HTML color; either a [6-digit hexadecimal RGB code](/en-US/docs/Web/CSS/hex-color), prefixed by a '`#`', or a [color keyword](/en-US/docs/Web/CSS/named-color). Other CSS {{cssxref("color_value", "&lt;color&gt")}} values are not supported. Use the {{cssxref("background-color")}} CSS property instead, as this attribute is deprecated. - `char` {{deprecated_inline}} - : Specifies the alignment of the content to a character of each column group cell. Typical values for this include a period (`.`) when attempting to align numbers or monetary values. If [`align`](#align) is not set to `char`, this attribute is ignored, though it will still be used as the default value for the [`align`](/en-US/docs/Web/HTML/Element/col#align) of the {{HTMLElement("col")}} elements which are members of this column group. - `charoff` {{deprecated_inline}} - : Specifies the number of characters to offset the column group cell content from the alignment character specified by the [`char`](#char) attribute. - `valign` {{deprecated_inline}} - : Specifies the vertical alignment of each column group cell. The possible {{Glossary("enumerated")}} values are `baseline`, `bottom`, `middle`, and `top`. Note that the descendant {{HTMLElement("col")}} elements may override this value using their own [`valign`](/en-US/docs/Web/HTML/Element/col#valign) attribute. Use the {{cssxref("vertical-align")}} CSS property on the {{htmlelement("td")}} and {{htmlelement("th")}} elements instead, as this attribute is deprecated. > **Note:** Setting `vertical-align` on the `<colgroup>` element has no effect as {{HTMLElement("td")}} and {{HTMLElement("th")}} elements are not descendants of the `<colgroup>` element, and therefore they do not inherit from it. > > If the table does not use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, use the [`td:nth-of-type()`](/en-US/docs/Web/CSS/:nth-of-type) CSS selector per column, e.g. `td:nth-of-type(2) { vertical-align: middle; }` to center the second column cells vertically. > > If the table does use a [`colspan`](/en-US/docs/Web/HTML/Element/td#colspan) attribute, the effect can be achieved by combining adequate CSS attribute selectors like `[colspan=n]`, though this is not trivial. - `width` {{deprecated_inline}} - : Specifies a default width for each column in the current column group. In addition to the standard pixel and percentage values, this attribute can take the special form `0*`, which means that the width of each column spanned should be the minimum width necessary to hold the column's contents. Relative widths such as `5*` can also be used. Note that the descendant {{HTMLElement("col")}} elements may override this value using their own [`width`](/en-US/docs/Web/HTML/Element/col#width) attribute. Use the {{cssxref("width")}} CSS property instead, as this attribute is deprecated. ## Usage notes - The `<colgroup>` should appear within a {{HTMLElement("table")}}, after any {{HTMLElement("caption")}} element (if used), but before any {{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, and {{HTMLElement("tr")}} elements. - Only a limited number of CSS properties affect `<colgroup>`: - {{cssxref("background")}} : The various `background` properties will set the background for cells within the column group. As the column group background color is painted on top of the table, but behind background colors applied to the columns ({{HTMLElement("col")}}), the row groups ({{htmlelement("thead")}}, {{htmlelement("tbody")}}, and {{htmlelement("tfoot")}}), the rows ({{htmlelement("tr")}}), and the individual cells ({{htmlelement("th")}} and {{htmlelement("td")}}), backgrounds applied to table column groups are only visible if every layer painted on top of them has a transparent background. - {{cssxref("border")}}: The various `border` properties apply, but only if the `<table>` has {{cssxref("border-collapse", "border-collapse: collapse")}} set. - {{cssxref("visibility")}}: The value `collapse` for a column group results in all cells of the columns in that column group not being rendered, and cells spanning into other columns being clipped. The space these columns in the column group would have occupied is removed. However, the size of other columns is still calculated as though the cells in the collapsed column(s) in the column group are present. Other values for `visibility` have no effect. - {{cssxref("width")}}: The `width` property defines a minimum width for the columns within the column group, as if {{cssxref("min-width")}} were set. ## Example See {{HTMLElement("table")}} for a complete table example introducing common standards and best practices. This example demonstrates a seven-column table divided into two `<colgroup>` elements that span multiple columns. ### HTML Two `<colgroup>` elements are used to structure a basic table by creating column groups. The number of columns in each column group is specified by the [`span`](#span) attribute. ```html <table> <caption> Personal weekly activities </caption> <colgroup span="5" class="weekdays"></colgroup> <colgroup span="2" class="weekend"></colgroup> <tr> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> <th>Sun</th> </tr> <tr> <td>Clean room</td> <td>Football training</td> <td>Dance Course</td> <td>History Class</td> <td>Buy drinks</td> <td>Study hour</td> <td>Free time</td> </tr> <tr> <td>Yoga</td> <td>Chess Club</td> <td>Meet friends</td> <td>Gymnastics</td> <td>Birthday party</td> <td>Fishing trip</td> <td>Free time</td> </tr> </table> ``` ### CSS Grouped columns can be used to visually highlight the structure using CSS: ```css table { border-collapse: collapse; border: 2px solid rgb(140 140 140); } caption { caption-side: bottom; padding: 10px; } th, td { border: 1px solid rgb(160 160 160); padding: 8px 6px; text-align: center; } .weekdays { background-color: #d7d9f2; } .weekend { background-color: #ffe8d4; } ``` ```css hidden table { font-family: sans-serif; font-size: 0.8rem; letter-spacing: 1px; } ``` #### Result {{EmbedLiveSample('Example', 650, 170)}} ## Technical summary <table class="properties"> <tbody> <tr> <th scope="row"> <a href="/en-US/docs/Web/HTML/Content_categories" >Content categories</a > </th> <td>None.</td> </tr> <tr> <th scope="row">Permitted content</th> <td> If the <a href="/en-US/docs/Web/HTML/Element/colgroup#span"><code>span</code></a> attribute is present: none.<br />If the attribute is not present: zero or more {{HTMLElement("col")}} element </td> </tr> <tr> <th scope="row">Tag omission</th> <td> The start tag may be omitted, if it has a {{HTMLElement("col")}} element as its first child and if it is not preceded by a {{HTMLElement("colgroup")}} whose end tag has been omitted.<br />The end tag may be omitted, if it is not followed by a space or a comment. </td> </tr> <tr> <th scope="row">Permitted parents</th> <td> A {{HTMLElement("table")}} element. The {{HTMLElement("colgroup")}} must appear after any {{HTMLElement("caption")}} element, but before any {{HTMLElement("thead")}}, {{HTMLElement("tbody")}}, {{HTMLElement("tfoot")}}, and {{HTMLElement("tr")}} elements. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="https://www.w3.org/TR/html-aria/#dfn-no-corresponding-role" >No corresponding role</a > </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td>No <code>role</code> permitted</td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLTableColElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Learn: HTML tables](/en-US/docs/Learn/HTML/Tables) - {{HTMLElement("caption")}}, {{HTMLElement("col")}}, {{HTMLElement("table")}}, {{HTMLElement("tbody")}}, {{HTMLElement("td")}}, {{HTMLElement("tfoot")}}, {{HTMLElement("th")}}, {{HTMLElement("thead")}}, {{HTMLElement("tr")}}: Other table-related elements - {{cssxref("background-color")}}: CSS property to set the background color of each column group cell - {{cssxref("border")}}: CSS property to control borders of column group cells - {{cssxref("text-align")}}: CSS property to horizontally align each column group cell content - {{cssxref("vertical-align")}}: CSS property to vertically align each column group cell content - {{cssxref("visibility")}}: CSS property to hide (or show) cells of a column group - {{cssxref("width")}}: CSS property to control the default width for each column in a column group - {{cssxref(":nth-of-type")}}, {{cssxref(":first-of-type")}}, {{cssxref(":last-of-type")}}: CSS pseudo-classes to select the desired column cells
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/dialog/index.md
--- title: "<dialog>: The Dialog element" slug: Web/HTML/Element/dialog page-type: html-element browser-compat: html.elements.dialog --- {{HTMLSidebar}} The **`<dialog>`** [HTML](/en-US/docs/Web/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 {{domxref("HTMLDialogElement.showModal()", ".showModal()")}} method to display a modal dialog and the {{domxref("HTMLDialogElement.show()", ".show()")}} method to display a non-modal dialog. The dialog box can be closed using the {{domxref("HTMLDialogElement.close()", ".close()")}} method or using the [`dialog`](/en-US/docs/Web/HTML/Element/form#method) method when submitting a `<form>` that is nested within the `<dialog>` element. Modal dialogs can also be closed by pressing the <kbd>Esc</kbd> key. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). > **Warning:** The `tabindex` attribute must not be used on the `<dialog>` element. See [usage notes](#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 {{HTMLElement("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"`](/en-US/docs/Web/HTML/Element/input#formmethod) 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 {{domxref("HTMLDialogElement.returnValue", "returnValue")}} property gets set to the value of the button that was activated. - The CSS {{cssxref('::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 {{domxref("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`](/en-US/docs/Web/HTML/Global_attributes/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 {{EmbedLiveSample("HTML-only_dialog", "100%", 200)}} > **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 {{domxref("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](/en-US/docs/Web/CSS/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 <kbd>Esc</kbd> 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`](/en-US/docs/Web/HTML/Global_attributes/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 {{cssxref('::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 {{EmbedLiveSample("Creating_a_modal_dialog", "100%", 200)}} 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`](/en-US/docs/Web/API/HTMLDialogElement/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 {{HTMLElement("select")}} and two {{HTMLElement("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 <kbd>Esc</kbd> key, the `returnValue` is not updated, and the `close` event doesn't occur, so the text in the {{HTMLElement("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 {{EmbedLiveSample("Handling the return value from the dialog", "100%", 300)}} 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](#html-only_dialog)). - By pressing the <kbd>Esc</kbd> key. - By calling the {{domxref("HTMLDialogElement.close()")}} method (as seen in the [modal example](#creating_a_modal_dialog)). In this example, the "Cancel" button closes the dialog via the `dialog` form method and the "Confirm" button closes the dialog via the {{domxref("HTMLDialogElement.close()")}} method. The "Cancel" button includes the [`formmethod="dialog"`](/en-US/docs/Web/HTML/Element/input/submit#formmethod) attribute, which overrides the {{HTMLElement("form")}}'s default {{HTTPMethod("GET")}} method. When a form's method is [`dialog`](#usage_notes), the state of the form is saved but not submitted, and the dialog gets closed. Without an `action`, submitting the form via the default {{HTTPMethod("GET")}} method causes a page to reload. We use JavaScript to prevent the submission and close the dialog with the {{domxref("event.preventDefault()")}} and {{domxref("HTMLDialogElement.close()")}} methods, respectively. It is important to provide a closing mechanism within every `dialog` element. The <kbd>Esc</kbd> 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`](/en-US/docs/Web/HTML/Element/input#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> ``` ```css hidden [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 {{EmbedLiveSample("Closing a dialog with a required form input", "100%", 300)}} 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;`](/en-US/docs/Web/CSS/display) when hidden and `display: block;` when shown, as well as being removed from / added to the {{glossary("top layer")}} and the [accessibility tree](/en-US/docs/Web/Performance/How_browsers_work#building_the_accessibility_tree). Therefore, for `<dialog>` elements to be animated the {{cssxref("display")}} property needs to be animatable. [Supporting browsers](/en-US/docs/Web/CSS/display#browser_compatibility) animate `display` with a variation on the [discrete animation type](/en-US/docs/Web/CSS/CSS_animated_properties#discrete). 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](/en-US/docs/Web/CSS/CSS_transitions), [`transition-behavior: allow-discrete`](/en-US/docs/Web/CSS/transition-behavior) needs to be set to enable the above behavior. This behavior is available by default when animating with [CSS animations](/en-US/docs/Web/CSS/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`](/en-US/docs/Web/CSS/@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`](/en-US/docs/Web/CSS/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`](/en-US/docs/Web/CSS/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. - {{cssxref("transition-behavior")}} property - : Set `transition-behavior: allow-discrete` on the `display` and `overlay` transitions (or on the {{cssxref("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 {{cssxref("background-color")}} property on the [`::backdrop`](/en-US/docs/Web/CSS/::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: {{ EmbedLiveSample("Transitioning dialog elements", "100%", "200") }} > **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](/en-US/docs/Web/CSS/@starting-style#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: {{ EmbedLiveSample("dialog keyframe animations", "100%", "200") }} ## Accessibility concerns When implementing a dialog, it is important to consider the most appropriate place to set user focus. When using {{domxref("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`](/en-US/docs/Web/HTML/Global_attributes/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 <kbd>Esc</kbd> key. A non-modal dialog does not dismiss via the <kbd>Esc</kbd> key by default, and depending on what the non-modal dialog represents, it may not be desired for this behavior. Keyboard users expect the <kbd>Esc</kbd> key to close modal dialogs; ensure that this behavior is implemented and maintained. If multiple modal dialogs are open, pressing the <kbd>Esc</kbd> 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"](/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role) attribute. `<dialog>` elements invoked by the `showModal()` method implicitly have [aria-modal="true"](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal), 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`](/en-US/docs/Web/HTML/Global_attributes/inert) attribute. When using `<dialog>` along with the `HTMLDialogElement.showModal()` method, this behavior is provided by the browser. ## 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_roots">sectioning root</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> </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role">dialog</a> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/alertdialog_role"><code>alertdialog</code></a></td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLDialogElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLDialogElement")}} interface - {{domxref("HTMLDialogElement/close_event", "close")}} event - {{domxref("HTMLElement/cancel_event", "cancel")}} event - {{domxref("HTMLDialogElement/open", "open")}} property of the `HTMLDialogElement` interface - [`inert`](/en-US/docs/Web/HTML/Global_attributes/inert) global attribute for HTML elements - {{CSSXref("::backdrop")}} CSS pseudo-element - [Web forms](/en-US/docs/Learn/Forms) in the Learn area
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/a/index.md
--- title: "<a>: The Anchor element" slug: Web/HTML/Element/a page-type: html-element browser-compat: html.elements.a --- {{HTMLSidebar}} The **`<a>`** [HTML](/en-US/docs/Web/HTML) element (or _anchor_ element), with [its `href` attribute](#href), creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address. Content within each `<a>` _should_ indicate the link's destination. If the `href` attribute is present, pressing the enter key while focused on the `<a>` element will activate it. {{EmbedInteractiveExample("pages/tabbed/a.html", "tabbed-shorter")}} ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `download` - : Causes the browser to treat the linked URL as a download. Can be used with or without a `filename` value: - Without a value, the browser will suggest a filename/extension, generated from various sources: - The {{HTTPHeader("Content-Disposition")}} HTTP header - The final segment in the URL [path](/en-US/docs/Web/API/URL/pathname) - The {{Glossary("MIME_type", "media type")}} (from the {{HTTPHeader("Content-Type")}} header, the start of a [`data:` URL](/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs), or {{domxref("Blob.type")}} for a [`blob:` URL](/en-US/docs/Web/API/URL/createObjectURL_static)) - `filename`: defining a value suggests it as the filename. `/` and `\` characters are converted to underscores (`_`). Filesystems may forbid other characters in filenames, so browsers will adjust the suggested name if necessary. > **Note:** > > - `download` only works for [same-origin URLs](/en-US/docs/Web/Security/Same-origin_policy), or the `blob:` and `data:` schemes. > - How browsers treat downloads varies by browser, user settings, and other factors. The user may be prompted before a download starts, or the file may be saved automatically, or it may open automatically, either in an external application or in the browser itself. > - If the `Content-Disposition` header has different information from the `download` attribute, resulting behavior may differ: > > - If the header specifies a `filename`, it takes priority over a filename specified in the `download` attribute. > - If the header specifies a disposition of `inline`, Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline. - `href` - : The URL that the hyperlink points to. Links are not restricted to HTTP-based URLs — they can use any URL scheme supported by browsers: - Sections of a page with document fragments - Specific text portions with [text fragments](/en-US/docs/Web/Text_fragments) - Pieces of media files with media fragments - Telephone numbers with `tel:` URLs - Email addresses with `mailto:` URLs - SMS text messages with `sms:` URLs - While web browsers may not support other URL schemes, websites can with [`registerProtocolHandler()`](/en-US/docs/Web/API/Navigator/registerProtocolHandler) - `hreflang` - : Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as [the global `lang` attribute](/en-US/docs/Web/HTML/Global_attributes/lang). - `ping` - : A space-separated list of URLs. When the link is followed, the browser will send {{HTTPMethod("POST")}} requests with the body `PING` to the URLs. Typically for tracking. - `referrerpolicy` - : How much of the [referrer](/en-US/docs/Web/HTTP/Headers/Referer) to send when following the link. - `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. - `rel` - : The relationship of the linked URL as space-separated link types. - `target` - : Where to display the linked URL, as the name for a _browsing context_ (a tab, window, or {{HTMLElement("iframe")}}). The following keywords have special meanings for where to load the URL: - `_self`: the current browsing context. (Default) - `_blank`: usually a new tab, but users can configure browsers to open a new window instead. - `_parent`: the parent browsing context of the current one. If no parent, behaves as `_self`. - `_top`: the topmost browsing context (the "highest" context that's an ancestor of the current one). If no ancestors, behaves as `_self`. > **Note:** Setting `target="_blank"` on `<a>` elements implicitly provides the same `rel` behavior as setting [`rel="noopener"`](/en-US/docs/Web/HTML/Attributes/rel/noopener) which does not set `window.opener`. - `type` - : Hints at the linked URL's format with a {{Glossary("MIME type")}}. No built-in functionality. ### Deprecated attributes - `charset` {{Deprecated_Inline}} - : Hinted at the {{Glossary("character encoding")}} of the linked URL. > **Note:** This attribute is deprecated and **should not be used by authors**. Use the HTTP {{HTTPHeader("Content-Type")}} header on the linked URL. - `coords` {{Deprecated_Inline}} - : Used with [the `shape` attribute](#shape). A comma-separated list of coordinates. - `name` {{Deprecated_Inline}} - : Was required to define a possible target location in a page. In HTML 4.01, `id` and `name` could both be used on `<a>`, as long as they had identical values. > **Note:** Use the global attribute [`id`](/en-US/docs/Web/HTML/Global_attributes#id) instead. - `rev` {{Deprecated_Inline}} - : Specified a reverse link; the opposite of [the `rel` attribute](#rel). Deprecated for being very confusing. - `shape` {{Deprecated_Inline}} - : The shape of the hyperlink's region in an image map. > **Note:** Use the {{HTMLElement("area")}} element for image maps instead. ## Examples ### Linking to an absolute URL #### HTML ```html <a href="https://www.mozilla.com">Mozilla</a> ``` #### Result {{EmbedLiveSample('Linking_to_an_absolute_URL')}} ### Linking to relative URLs #### HTML ```html <a href="//example.com">Scheme-relative URL</a> <a href="/en-US/docs/Web/HTML">Origin-relative URL</a> <a href="./p">Directory-relative URL</a> ``` ```css hidden a { display: block; margin-bottom: 0.5em; } ``` #### Result {{EmbedLiveSample('Linking_to_relative_URLs')}} ### Linking to an element on the same page ```html <!-- <a> element links to the section below --> <p><a href="#Section_further_down">Jump to the heading below</a></p> <!-- Heading to link to --> <h2 id="Section_further_down">Section further down</h2> ``` #### Result {{EmbedLiveSample('Linking to an element on the same page')}} > **Note:** You can use `href="#top"` or the empty fragment (`href="#"`) to link to the top of the current page, [as defined in the HTML specification](https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier). ### Linking to an email address To create links that open in the user's email program to let them send a new message, use the `mailto:` scheme: ```html <a href="mailto:[email protected]">Send email to nowhere</a> ``` #### Result {{EmbedLiveSample('Linking to an email address')}} For details about `mailto:` URLs, such as including a subject or body, see [Email links](/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#email_links) or {{RFC(6068)}}. ### Linking to telephone numbers ```html <a href="tel:+49.157.0156">+49 157 0156</a> <a href="tel:+1(800)555-0123">(800) 555-0123</a> ``` #### Result {{EmbedLiveSample('Linking to telephone numbers')}} `tel:` link behavior varies with device capabilities: - Cellular devices autodial the number. - Most operating systems have programs that can make calls, like Skype or FaceTime. - Websites can make phone calls with {{domxref("Navigator/registerProtocolHandler", "registerProtocolHandler")}}, such as `web.skype.com`. - Other behaviors include saving the number to contacts, or sending the number to another device. See {{RFC(3966)}} for syntax, additional features, and other details about the `tel:` URL scheme. ### Using the download attribute to save a \<canvas> as a PNG To save a {{HTMLElement("canvas")}} element's contents as an image, you can create a link where the `href` is the canvas data as a `data:` URL created with JavaScript and the `download` attribute provides the file name for the downloaded PNG file: #### Example painting app with save link ##### HTML ```html <p> Paint by holding down the mouse button and moving it. <a href="" download="my_painting.png">Download my painting</a> </p> <canvas width="300" height="300"></canvas> ``` ##### CSS ```css html { font-family: sans-serif; } canvas { background: #fff; border: 1px dashed; } a { display: inline-block; background: #69c; color: #fff; padding: 5px 10px; } ``` ##### JavaScript ```js const canvas = document.querySelector("canvas"); const c = canvas.getContext("2d"); c.fillStyle = "hotpink"; let isDrawing; function draw(x, y) { if (isDrawing) { c.beginPath(); c.arc(x, y, 10, 0, Math.PI * 2); c.closePath(); c.fill(); } } canvas.addEventListener("mousemove", (event) => draw(event.offsetX, event.offsetY), ); canvas.addEventListener("mousedown", () => (isDrawing = true)); canvas.addEventListener("mouseup", () => (isDrawing = false)); document .querySelector("a") .addEventListener( "click", (event) => (event.target.href = canvas.toDataURL()), ); ``` ##### Result {{EmbedLiveSample('Example_painting_app_with_save_link', '100%', '400')}} ## Security and privacy `<a>` elements can have consequences for users' security and privacy. See [`Referer` header: privacy and security concerns](/en-US/docs/Web/Security/Referer_header:_privacy_and_security_concerns) for information. Using `target="_blank"` without [`rel="noreferrer"`](/en-US/docs/Web/HTML/Attributes/rel/noreferrer) and [`rel="noopener"`](/en-US/docs/Web/HTML/Attributes/rel/noopener) makes the website vulnerable to {{domxref("window.opener")}} API exploitation attacks, although note that, in newer browser versions setting `target="_blank"` implicitly provides the same protection as setting `rel="noopener"`. See [browser compatibility](#browser_compatibility) for details. ## Accessibility concerns ### Strong link text **The content inside a link should indicate where the link goes**, even out of context. #### Inaccessible, weak link text A sadly common mistake is to only link the words "click here" or "here": ```html example-bad <p>Learn more about our products <a href="/products">here</a>.</p> ``` ##### Result {{EmbedLiveSample('Inaccessible, weak link text')}} #### Strong link text Luckily, this is an easy fix, and it's actually shorter than the inaccessible version! ```html example-good <p>Learn more <a href="/products">about our products</a>.</p> ``` ##### Result {{EmbedLiveSample('Strong link text')}} Assistive software has shortcuts to list all links on a page. However, strong link text benefits all users — the "list all links" shortcut emulates how sighted users quickly scan pages. ### onclick events Anchor elements are often abused as fake buttons by setting their `href` to `#` or `javascript:void(0)` to prevent the page from refreshing, then listening for their `click` events . These bogus `href` values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers. Use a {{HTMLElement("button")}} instead. In general, **you should only use a hyperlink for navigation to a real URL**. ### External links and linking to non-HTML resources Links that open in a new tab/window via `target="_blank"`, or links that point to a download file should indicate what will happen when the link is followed. People experiencing low vision conditions, navigating with the aid of screen reading technology, or with cognitive concerns may be confused when a new tab, window, or application opens unexpectedly. Older screen-reading software may not even announce the behavior. #### Link that opens a new tab/window ```html <a target="_blank" href="https://www.wikipedia.org"> Wikipedia (opens in new tab) </a> ``` ##### Result {{EmbedLiveSample('Link that opens a new tab/window')}} #### Link to a non-HTML resource ```html <a href="2017-annual-report.ppt">2017 Annual Report (PowerPoint)</a> ``` If an icon is used to signify link behavior, make sure it has an [_alt text_](/en-US/docs/Web/HTML/Element/img#alt): ```html <a target="_blank" href="https://www.wikipedia.org"> Wikipedia <img alt="(opens in new tab)" src="newtab.svg" /> </a> <a href="2017-annual-report.ppt"> 2017 Annual Report <img alt="(PowerPoint file)" src="ppt-icon.svg" /> </a> ``` ##### Result {{EmbedLiveSample('Link to a non-HTML resource')}} - [WebAIM: Links and Hypertext - Hypertext Links](https://webaim.org/techniques/hypertext/hypertext_links) - [MDN / Understanding WCAG, Guideline 3.2](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.2_—_predictable_make_web_pages_appear_and_operate_in_predictable_ways) - [G200: Opening new windows and tabs from a link only when necessary](https://www.w3.org/TR/WCAG20-TECHS/G200.html) - [G201: Giving users advanced warning when opening a new window](https://www.w3.org/TR/WCAG20-TECHS/G201.html) ### Skip links A **skip link** is a link placed as early as possible in {{HTMLElement("body")}} content that points to the beginning of the page's main content. Usually, CSS hides a skip link offscreen until focused. ```html <body> <a href="#content" class="skip-link">Skip to main content</a> <header>…</header> <!-- The skip link jumps to here --> <main id="content"></main> </body> ``` ```css .skip-link { position: absolute; top: -3em; background: #fff; } .skip-link:focus { top: 0; } ``` #### Result {{EmbedLiveSample('Skip links')}} Skip links let keyboard users bypass content repeated throughout multiple pages, such as header navigation. Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving through repetitive links can be laborious. - [WebAIM: "Skip Navigation" Links](https://webaim.org/techniques/skipnav/) - [How-to: Use Skip Navigation links](https://www.a11yproject.com/posts/skip-nav-links/) - [MDN / Understanding WCAG, Guideline 2.4 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.4_%e2%80%94_navigable_provide_ways_to_help_users_navigate_find_content_and_determine_where_they_are) - [Understanding Success Criterion 2.4.1](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-skip.html) ### Size and proximity #### Size Interactive elements, like links, should provide an area large enough that it is easy to activate them. This helps a variety of people, including those with motor control issues and those using imprecise inputs such as a touchscreen. A minimum size of 44×44 [CSS pixels](https://www.w3.org/TR/WCAG21/#dfn-css-pixels) is recommended. Text-only links in prose content are exempt from this requirement, but it's still a good idea to make sure enough text is hyperlinked to be easily activated. - [Understanding Success Criterion 2.5.5: Target Size](https://www.w3.org/WAI/WCAG21/Understanding/target-size.html) - [Target Size and 2.5.5](https://adrianroselli.com/2019/06/target-size-and-2-5-5.html) - [Quick test: Large touch targets](https://www.a11yproject.com/posts/large-touch-targets/) #### Proximity Interactive elements, like links, placed in close visual proximity should have space separating them. Spacing helps people with motor control issues, who may otherwise accidentally activate the wrong interactive content. Spacing may be created using CSS properties like {{CSSxRef("margin")}}. - [Hand tremors and the giant-button-problem](https://axesslab.com/hand-tremors/) ## 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 >, palpable content. </td> </tr> <tr> <th scope="row">Permitted content</th> <td> <a href="/en-US/docs/Web/HTML/Content_categories#transparent_content_model" >Transparent</a >, except that no descendant may be <a href="/en-US/docs/Web/HTML/Content_categories#interactive_content" >interactive content</a > or an <a href="/en-US/docs/Web/HTML/Element/a" >a</a > element, and no descendant may have a specified <a href="/en-US/docs/Web/HTML/Global_attributes/tabindex" >tabindex</a > attribute. </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 not other <code>&#x3C;a></code> elements. </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> when <code>href</code> attribute is present, otherwise <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/generic_role"><code>generic</code></a> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <p>When <code>href</code> attribute is present:</p> <ul> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role"><code>button</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role"><code>checkbox</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitem_role"><code>menuitem</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemcheckbox_role"><code>menuitemcheckbox</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/menuitemradio_role"><code>menuitemradio</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/option_role"><code>option</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/radio_role"><code>radio</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/switch_role"><code>switch</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role"><code>tab</code></a></li> <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/treeitem_role"><code>treeitem</code></a></li> </ul> <p>When <code>href</code> attribute is not present:</p> <ul> <li>any</li> </ul> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{DOMxRef("HTMLAnchorElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("link")}} is similar to `<a>`, but for metadata hyperlinks that are invisible to users. - {{CSSxRef(":link")}} is a CSS pseudo-class that will match `<a>` elements with URL in `href` attribute that was not yet visited by the user. - {{CSSxRef(":visited")}} is a CSS pseudo-class that will match `<a>` elements with URL in `href` attribute that was visited by the user in the past. - {{CSSxRef(":any-link")}} is a CSS pseudo-class that will match `<a>` elements with `href` attribute. - [Text fragments](/en-US/docs/Web/Text_fragments) are user-agent instructions added to URLs that allow content authors to link to specific text on a page, without IDs being required.
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/footer/index.md
--- title: "<footer>: The Footer element" slug: Web/HTML/Element/footer page-type: html-element browser-compat: html.elements.footer --- {{HTMLSidebar}} The **`<footer>`** [HTML](/en-US/docs/Web/HTML) element represents a footer for its nearest ancestor [sectioning content](/en-US/docs/Web/HTML/Content_categories#sectioning_content) or [sectioning root](/en-US/docs/Web/HTML/Element/Heading_Elements#sectioning_root) element. A `<footer>` typically contains information about the author of the section, copyright data or links to related documents. {{EmbedInteractiveExample("pages/tabbed/footer.html", "tabbed-standard")}} ## Attributes This element only includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). ## Usage notes - Enclose information about the author in an {{HTMLElement("address")}} element that can be included into the `<footer>` element. - When the nearest ancestor sectioning content or sectioning root element is the body element the footer applies to the whole page. - The `<footer>` element is not sectioning content and therefore doesn't introduce a new section in the [outline](/en-US/docs/Web/HTML/Element/Heading_Elements). ## Examples ```html <body> <h3>FIFA World Cup top goalscorers</h3> <ol> <li>Miroslav Klose, 16</li> <li>Ronaldo Nazário, 15</li> <li>Gerd Müller, 14</li> </ol> <footer> <small> Copyright © 2023 Football History Archives. All Rights Reserved. </small> </footer> </body> ``` ```css footer { text-align: center; padding: 5px; background-color: #abbaba; color: #000; } ``` {{EmbedLiveSample('Examples')}} ## Accessibility concerns Prior to the release of Safari 13, the `contentinfo` [landmark role](/en-US/docs/Learn/Accessibility/WAI-ARIA_basics#signpostslandmarks) was not properly exposed by [VoiceOver](https://help.apple.com/voiceover/info/guide/). If needing to support legacy Safari browsers, add `role="contentinfo"` to the `footer` element to ensure the landmark will be properly exposed. - Related: [WebKit Bugzilla: 146930 – AX: HTML native elements (header, footer, main, aside, nav) should work the same as ARIA landmarks, sometimes they don't](https://webkit.org/b/146930) ## 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 <code>&#x3C;footer></code> or {{HTMLElement("header")}} 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#flow_content">flow content</a>. Note that a <code>&#x3C;footer></code> element must not be a descendant of an {{HTMLElement("address")}}, {{HTMLElement("header")}} or another <code>&#x3C;footer></code> element. </td> </tr> <tr> <th scope="row">Implicit ARIA role</th> <td> <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Contentinfo_role">contentinfo</a>, or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Generic_role">generic</a> if a descendant of an <a href="/en-US/docs/Web/HTML/Element/article">article</a>, <a href="/en-US/docs/Web/HTML/Element/aside">aside</a>, <a href="/en-US/docs/Web/HTML/Element/main">main</a>, <a href="/en-US/docs/Web/HTML/Element/nav">nav</a> or <a href="/en-US/docs/Web/HTML/Element/section">section</a> element, or an element with <code>role=<a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Article_Role">article</a></code>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Complementary_role">complementary</a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Main_role">main</a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Navigation_Role">navigation</a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Region_role">region</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>, <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("hgroup")}}, {{HTMLElement("header")}}, {{HTMLElement("section")}}, {{HTMLElement("address")}}; - [Using HTML sections and outlines](/en-US/docs/Web/HTML/Element/Heading_Elements) - [ARIA: Contentinfo role](/en-US/docs/Web/Accessibility/ARIA/Roles/contentinfo_role)
0
data/mdn-content/files/en-us/web/html/element
data/mdn-content/files/en-us/web/html/element/form/index.md
--- title: "<form>: The Form element" slug: Web/HTML/Element/form page-type: html-element browser-compat: html.elements.form --- {{HTMLSidebar}} The **`<form>`** [HTML](/en-US/docs/Web/HTML) element represents a document section containing interactive controls for submitting information. {{EmbedInteractiveExample("pages/tabbed/form.html", "tabbed-standard")}} It is possible to use the {{cssxref(':valid')}} and {{cssxref(':invalid')}} CSS [pseudo-classes](/en-US/docs/Web/CSS/Pseudo-classes) to style a `<form>` element based on whether the {{domxref("HTMLFormElement.elements", "elements")}} inside the form are valid. ## Attributes This element includes the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `accept` {{deprecated_inline}} - : Comma-separated [content types](/en-US/docs/Web/SVG/Content_type) the server accepts. > **Note:** **This attribute has been deprecated and should not be used.** Instead, use the [`accept`](/en-US/docs/Web/HTML/Element/input#accept) attribute on `<input type=file>` elements. - `accept-charset` - : Space-separated {{Glossary("character encoding", "character encodings")}} the server accepts. The browser uses them in the order in which they are listed. The default value means [the same encoding as the page](/en-US/docs/Web/HTTP/Headers/Content-Encoding). (In previous versions of HTML, character encodings could also be delimited by commas.) - `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` - : Indicates whether input elements can by default have their values automatically completed by the browser. `autocomplete` attributes on form elements override it on `<form>`. Possible values: - `off`: The browser may not automatically complete entries. (Browsers tend to ignore this for suspected login forms; see [The autocomplete attribute and login fields](/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion#the_autocomplete_attribute_and_login_fields).) - `on`: The browser may automatically complete entries. - `name` - : The name of the form. The value must not be the empty string, and must be unique among the `form` elements in the forms collection that it is in, if any. - `rel` - : Controls the annotations and what kinds of links the form creates. Annotations include [`external`](/en-US/docs/Web/HTML/Attributes/rel#external), [`nofollow`](/en-US/docs/Web/HTML/Attributes/rel#nofollow), [`opener`](/en-US/docs/Web/HTML/Attributes/rel#opener), [`noopener`](/en-US/docs/Web/HTML/Attributes/rel#noopener), and [`noreferrer`](/en-US/docs/Web/HTML/Attributes/rel#noreferrer). Link types include [`help`](/en-US/docs/Web/HTML/Attributes/rel#help), [`prev`](/en-US/docs/Web/HTML/Attributes/rel#prev), [`next`](/en-US/docs/Web/HTML/Attributes/rel#next), [`search`](/en-US/docs/Web/HTML/Attributes/rel#search), and [`license`](/en-US/docs/Web/HTML/Attributes/rel#license). The [`rel`](/en-US/docs/Web/HTML/Attributes/rel) value is a space-separated list of these enumerated values. ### Attributes for form submission The following attributes control behavior during form submission. - `action` - : The URL that processes the form submission. This value can be overridden by a [`formaction`](/en-US/docs/Web/HTML/Element/button#formaction) attribute on a {{HTMLElement("button")}}, [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit), or [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) element. This attribute is ignored when `method="dialog"` is set. - `enctype` - : If the value of the `method` attribute is `post`, `enctype` is the [MIME type](https://en.wikipedia.org/wiki/Mime_type) of the form submission. Possible values: - `application/x-www-form-urlencoded`: The default value. - `multipart/form-data`: Use this if the form contains {{HTMLElement("input")}} elements with `type=file`. - `text/plain`: Useful for debugging purposes. This value can be overridden by [`formenctype`](/en-US/docs/Web/HTML/Element/button#formenctype) attributes on {{HTMLElement("button")}}, [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit), or [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) elements. - `method` - : The [HTTP](/en-US/docs/Web/HTTP) method to submit the form with. The only allowed methods/values are (case insensitive): - `post`: The {{HTTPMethod("POST")}} method; form data sent as the [request body](/en-US/docs/Web/API/Request/body). - `get` (default): The {{HTTPMethod("GET")}}; form data appended to the `action` URL with a `?` separator. Use this method when the form [has no side effects](/en-US/docs/Glossary/Idempotent). - `dialog`: When the form is inside a {{HTMLElement("dialog")}}, closes the dialog and causes a `submit` event to be fired on submission, without submitting data or clearing the form. This value is overridden by [`formmethod`](/en-US/docs/Web/HTML/Element/button#formmethod) attributes on {{HTMLElement("button")}}, [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit), or [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) elements. - `novalidate` - : This Boolean attribute indicates that the form shouldn't be validated when submitted. If this attribute is not set (and therefore the form **_is_** validated), it can be overridden by a [`formnovalidate`](/en-US/docs/Web/HTML/Element/button#formnovalidate) attribute on a {{HTMLElement("button")}}, [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit), or [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) element belonging to the form. - `target` - : Indicates where to display the response after submitting the form. It is a name/keyword for a _browsing context_ (for example, tab, window, or iframe). The following keywords have special meanings: - `_self` (default): Load into the same browsing context as the current one. - `_blank`: Load into a new unnamed browsing context. This provides the same behavior as setting [`rel="noopener"`](#rel) which does not set [`window.opener`](/en-US/docs/Web/API/Window/opener). - `_parent`: Load into the parent browsing context of the current one. If no parent, behaves the same as `_self`. - `_top`: Load into the top-level browsing context (i.e., the browsing context that is an ancestor of the current one and has no parent). If no parent, behaves the same as `_self`. This value can be overridden by a [`formtarget`](/en-US/docs/Web/HTML/Element/button#formtarget) attribute on a {{HTMLElement("button")}}, [`<input type="submit">`](/en-US/docs/Web/HTML/Element/input/submit), or [`<input type="image">`](/en-US/docs/Web/HTML/Element/input/image) element. ## Examples ```html <!-- Form which will send a GET request to the current URL --> <form method="get"> <label> Name: <input name="submitted-name" autocomplete="name" /> </label> <button>Save</button> </form> <!-- Form which will send a POST request to the current URL --> <form method="post"> <label> Name: <input name="submitted-name" autocomplete="name" /> </label> <button>Save</button> </form> <!-- Form with fieldset, legend, and label --> <form method="post"> <fieldset> <legend>Do you agree to the terms?</legend> <label><input type="radio" name="radio" value="yes" /> Yes</label> <label><input type="radio" name="radio" value="no" /> No</label> </fieldset> </form> ``` ### 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#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 not containing <code>&#x3C;form></code> 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/form_role">form</a></code> </td> </tr> <tr> <th scope="row">Permitted ARIA roles</th> <td> <code><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/search_role">search</a></code>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/none_role"><code>none</code></a> or <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/presentation_role"><code>presentation</code></a> </td> </tr> <tr> <th scope="row">DOM interface</th> <td>{{domxref("HTMLFormElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [HTML forms guide](/en-US/docs/Learn/Forms) - Other elements that are used when creating forms: {{HTMLElement("button")}}, {{HTMLElement("datalist")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}, {{HTMLElement("label")}}, {{HTMLElement("legend")}}, {{HTMLElement("meter")}}, {{HTMLElement("optgroup")}}, {{HTMLElement("option")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("select")}}, {{HTMLElement("textarea")}}. - Getting a list of the elements in the form: {{domxref("HTMLFormElement.elements")}} - [ARIA: Form role](/en-US/docs/Web/Accessibility/ARIA/Roles/form_role) - [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/data/index.md
--- title: "<data>: The Data element" slug: Web/HTML/Element/data page-type: html-element browser-compat: html.elements.data --- {{HTMLSidebar}} The **`<data>`** [HTML](/en-US/docs/Web/HTML) element links a given piece of content with a machine-readable translation. If the content is time- or date-related, the {{HTMLElement("time")}} element must be used. {{EmbedInteractiveExample("pages/tabbed/data.html", "tabbed-shorter")}} ## Attributes This element's attributes include the [global attributes](/en-US/docs/Web/HTML/Global_attributes). - `value` - : This attribute specifies the machine-readable translation of the content of the element. ## Examples The following example displays product names but also associates each name with a product number. ```html <p>New Products</p> <ul> <li><data value="398">Mini Ketchup</data></li> <li><data value="399">Jumbo Ketchup</data></li> <li><data value="400">Mega Jumbo Ketchup</data></li> </ul> ``` ### 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("HTMLDataElement")}}</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML {{HTMLElement("time")}} element.
0