The and <slot> elements in HTML5 can be developed componentically by defining HTML structures and dynamic content placeholders that are not rendered immediately. is used to create reusable DOM templates, rendered only when inserted into the DOM by JavaScript; <slot> is used as a content insertion point, allowing custom content to be filled in different usage scenarios. The combination of the two can be used to build UI components with unified structure and dynamic expansion capabilities, such as modal boxes or tab pages. When using it, you should pay attention to: test the default content of the slot, avoid excessive nesting, keep the template simple, deal with delayed execution of scripts, and pay attention to differences in slot behavior in Shadow DOM.
In modern web development, building reusable and modular components is a big part of creating maintainable user interfaces. HTML5 gives us two powerful tools for this: the <template></template>
and <slot></slot>
elements. They might not be as flashy as some JavaScript frameworks, but they're lightweight, native, and work right out of the box.

What <template></template>
does (and why it's useful)
The <template></template>
element lets you define chunks of HTML that aren't rendered immediately when the page loads. Think of it like a blueprint — it holds markup that you can clone and insert into the DOM later using JavaScript.

This is super handy if you want to reuse the same structure multiple times without duplicating code. For example, say you're building a list of cards that all look the same but have different content. You could write one template and stamp it out as many times as needed.
Here's a quick idea of how it works:

<template id="card-template"> <div class="card"> <h2>Title</h2> <p>Content goes here.</p> </div> </template>
Then in JavaScript:
const template = document.getElementById('card-template'); const clone = template.content.cloneNode(true); document.body.appendChild(clone);
No rendering until you actually append it — simple and efficient.
How <slot>
fits into the picture
Now, what if you want to make your templates more dynamic? That's where <slot>
comes in. It acts like a placeholder inside a template or a custom element. You can pass in different content each time you use the template by putting it between the custom element tags.
Slots are especially useful with Web Components, but even outside of them, they help build flexible UI pieces. Here's a basic example:
<template id="panel-template"> <div class="panel"> <slot name="header">Default Header</slot> <div class="content"> <slot>Default Content</slot> </div> </div> </template>
When you use this somewhere else:
<my-panel> <h1 slot="header">Custom Title</h1> <p>This will replace the default content.</p> </my-panel>
You get a panel with your own header and content — without rewriting the whole thing every time.
When to combine <template></template>
and <slot></slot>
Using these two together makes sense when you're building reusable UI blocks that need both structure and flexibility. Templates give you the base layout, and slots let you inject variation where needed.
A common use case is creating custom elements. For instance, a reusable modal dialog component might have a template defining its overall layout, with slots for the title, body content, and actions.
Another example: tabs. Each tab panel could be based on a shared template, but the actual tab label and content would come from slots, making each tab unique while keeping the behavior consistent.
Some tips when working with them:
- Always test fallback content inside
<slot></slot>
in case nothing gets passed in. - Avoid deeply nested slots unless necessary — it can get confusing fast.
- Use named slots for clarity when there are multiple insertion points.
- Keep templates small and focused — don't overstuff them with too much logic.
A few gotchas to watch for
One thing that trips people up is forgetting that the content inside <template></template>
isn't active. Scripts won't run, images won't load, and styles won't apply until you actually put it into the DOM. So if you're planning to include any interactive bits, make sure you wire those up after cloning.
Also, slots inside shadow DOM (used in Web Components) behave differently than in regular templates. If you're mixing shadow DOM with <slot></slot>
, things like styling and event propagation might need extra attention.
And remember, just because something can be done with templates and slots doesn't always mean it should . Sometimes plain old HTML and a little JavaScript is better than over-engineering.
Basically that's it.
The above is the detailed content of Using the HTML5 `` and `` elements. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

HTML5isbetterforcontrolandcustomization,whileYouTubeisbetterforeaseandperformance.1)HTML5allowsfortailoreduserexperiencesbutrequiresmanagingcodecsandcompatibility.2)YouTubeofferssimpleembeddingwithoptimizedperformancebutlimitscontroloverappearanceand

Yes,youcanrecordaudioandvideo.Here'show:1)Foraudio,useasoundcheckscripttofindthequietestspotandtestlevels.2)Forvideo,useOpenCVtomonitorbrightnessandadjustlighting.3)Torecordbothsimultaneously,usethreadinginPythonforsynchronization,oroptforuser-friend

The way to add drag and drop functionality to a web page is to use HTML5's DragandDrop API, which is natively supported without additional libraries. The specific steps are as follows: 1. Set the element draggable="true" to enable drag; 2. Listen to dragstart, dragover, drop and dragend events; 3. Set data in dragstart, block default behavior in dragover, and handle logic in drop. In addition, element movement can be achieved through appendChild and file upload can be achieved through e.dataTransfer.files. Note: preventDefault must be called

Use and elements to add audio and video to HTML. 1) Use elements to embed audio, make sure to include controls attributes and alternate text. 2) Use elements to embed video, set width and height attributes, and provide multiple video sources to ensure compatibility. 3) Add subtitles to improve accessibility. 4) Optimize performance through adaptive bit rate streaming and delayed loading. 5) Avoid automatic playback unless muted, ensuring user control and a clear interface.

AnimatingSVGwithCSSispossibleusingkeyframesforbasicanimationsandtransitionsforinteractiveeffects.1.Use@keyframestodefineanimationstagesforpropertieslikescale,opacity,andcolor.2.ApplytheanimationtoSVGelementssuchas,,orviaCSSclasses.3.Forhoverorstate-b

inputtype="range" is used to create a slider control, allowing the user to select a value from a predefined range. 1. It is mainly suitable for scenes where values ??need to be selected intuitively, such as adjusting volume, brightness or scoring systems; 2. The basic structure includes min, max and step attributes, which set the minimum value, maximum value and step size respectively; 3. This value can be obtained and used in real time through JavaScript to improve the interactive experience; 4. It is recommended to display the current value and pay attention to accessibility and browser compatibility issues when using it.

Audio and video elements in HTML can improve the dynamics and user experience of web pages. 1. Embed audio files using elements and realize automatic and loop playback of background music through autoplay and loop properties. 2. Use elements to embed video files, set width and height and controls properties, and provide multiple formats to ensure browser compatibility.

WebRTC is a free, open source technology that supports real-time communication between browsers and devices. It realizes audio and video capture, encoding and point-to-point transmission through built-in API, without plug-ins. Its working principle includes: 1. The browser captures audio and video input; 2. The data is encoded and transmitted directly to another browser through a security protocol; 3. The signaling server assists in the initial connection but does not participate in media transmission; 4. The connection is established to achieve low-latency direct communication. The main application scenarios are: 1. Video conferencing (such as GoogleMeet, Jitsi); 2. Customer service voice/video chat; 3. Online games and collaborative applications; 4. IoT and real-time monitoring. Its advantages are cross-platform compatibility, no download required, default encryption and low latency, suitable for point-to-point communication
