Details and Summary in Practice
The earlier lesson on the Details element showed how details and summary make an expandable section with no JavaScript, how open works, how name builds an exclusive accordion, and how to style the marker. This lesson is about what happens in real pages: forms inside collapsed sections, links that point into them, nesting, animation, and knowing when something else fits better.
What You Will Learnโ
- Why a required field inside a closed section can quietly block a form
- How to open the right sections for a deep link
- How to structure a good summary
- How to add an optional animation
- How to load heavy content only when needed
- When not to use
details
The Big Ideaโ
details is the simplest way to hide and reveal content, and it works without any script. Real pages add small needs on top: "show the error", "open the section I linked to", "do not load that video yet". A few lines of script cover those, and the element keeps doing the heavy lifting.
- Form in a Section
- Deep Link Lab
- True or False?
- The Code
Press Send with the phone field empty and the section closed. Then tick the box, reset, and try again. How browsers handle an invalid field inside a closed section differs, which is why the extra line of script is worth adding.
Help centre
Payments
We accept cards and bank transfers.
Refunds
Refunds go back to the original payment method.
Late refunds
If a refund takes longer than ten working days, contact support.
The same idea is used to open the right sections when a visitor follows a link such as the address of a question in an FAQ.
True or false?
A link placed inside a summary is a good way to make the heading clickable.
Content inside a closed details element is still in the page source, and its form fields still belong to the form.
A details element closes by itself when the visitor clicks somewhere else on the page.
You may nest one details element inside another.
Following a link to an item inside a closed details always opens it, with no code from you.
Animating the opening of a details element is an optional enhancement.
<form id="order">
<label for="name">Name</label>
<input id="name" name="name" required>
<details id="delivery">
<summary>Delivery details</summary>
<label for="phone">Phone number</label>
<input id="phone" name="phone" type="tel" required>
</details>
<button type="submit">Send</button>
</form>
// 1. Open a section when a field inside it is invalid.
// The invalid event does not bubble, so listen in the capture phase.
document.getElementById("order").addEventListener("invalid", (event) => {
const section = event.target.closest("details");
if (section) section.open = true;
}, true);
// 2. Open every section around a link target.
function revealFromHash() {
let id;
try { id = decodeURIComponent(location.hash.slice(1)); } catch (e) { return; }
const target = id ? document.getElementById(id) : null;
if (!target) return;
let el = target.closest("details");
while (el) {
el.open = true;
el = el.parentElement ? el.parentElement.closest("details") : null;
}
target.scrollIntoView();
}
window.addEventListener("hashchange", revealFromHash);
revealFromHash();
Pattern 1: Forms Inside a Collapsed Sectionโ
Content in a closed details is still in the page, and still part of the form. Its fields are sent when the form is submitted, and checked when the browser validates the form.
That causes a classic trap. If a required field sits inside a closed section and is empty, the browser cannot show a message next to a field that is not displayed. Depending on the browser and version, the visitor may see an error in the Console, a section that quietly opens, or nothing at all. The form simply does not send, and they cannot tell why.
Try it in the first tab: press Send with the section closed, then turn on the checkbox, reset, and try again.
The fix is a few lines:
form.addEventListener("invalid", (event) => {
const section = event.target.closest("details");
if (section) section.open = true;
}, true);
- The
invalidevent fires on each field that fails validation, but it does not bubble, so you listen in the capture phase (the finaltrue). - Opening the section lets the browser focus the field and show its message.
- It is just as important to validate on the server, as covered in Secure Forms.
A simpler rule also helps: do not hide required fields. Keep optional fields in a collapsed section, and required ones in the open.
Pattern 2: Deep Links and Nested Sectionsโ
A common request is "link to that exact question in our FAQ". The link is easy: give the details an id, and link to #that-id. But the visitor may arrive with the section closed, or with a closed section around it.
Some browsers open a closed section when the address points inside it, and some do not, or only in certain cases. To be consistent, open the ancestors yourself, as in the code above. The Deep Link Lab does the same for a nested help centre: jump to "Late refunds" and watch every section on the way open.
Notes on nesting:
- It is allowed, but keep it shallow. Two levels are usually plenty.
- Give the sections that you link to an
id, and keep ids stable. Changing one breaks old links. - Move focus to the summary of the target, so keyboard and screen reader users land in the right place.
Pattern 3: A Good Summaryโ
The summary is the visitor's only clue to what is inside, so it needs to work on its own.
- Write it as a clear label or a question, such as "Can I return an item?", not "More".
- Keep it short, so it does not wrap into a block of text.
- Use text and simple inline elements. A heading can go inside a summary, but screen reader support for headings inside a summary varies, so test it if you rely on headings for navigation.
- Do not put links or buttons inside a summary. They compete with the toggle, and the result is confusing for everyone.
- Make it easy to tap. Give the summary generous padding, so it is a comfortable target on a phone.
Pattern 4: An Optional Animationโ
By default, a section jumps open. In browsers that support newer CSS, you can animate the height:
:root {
interpolate-size: allow-keywords;
}
details::details-content {
block-size: 0;
overflow: clip;
transition: block-size 0.25s ease, content-visibility 0.25s allow-discrete;
}
details[open]::details-content {
block-size: auto;
}
@media (prefers-reduced-motion: reduce) {
details::details-content {
transition: none;
}
}
This is a progressive enhancement: where the features are not supported, the section simply jumps open, as before. Always include the reduced-motion rule, and check the support of ::details-content and interpolate-size on MDN before relying on it.
Pattern 5: Load Heavy Content Lateโ
Content in a closed details is not displayed, so you can save work by keeping heavy things out of the first load. For a video, a map, or other embed:
<details>
<summary>Watch the video</summary>
<iframe src="https://video.example.net/embed/123" title="Product tour"
loading="lazy" width="560" height="315"></iframe>
</details>
With loading="lazy", the browser usually waits until the frame is near view, so a closed section does not pay for it. The same goes for lazy images. Check this in the Network panel for your browser, because behaviour can vary. If a third party is involved, see iFrame Security for sandbox and privacy points.
Pattern 6: Accordionsโ
You can build an exclusive accordion by giving several details the same name, as the earlier lesson explained. A few extra points from practice:
- Open at most one at the start, and consider opening none on small screens, to keep the page short.
- Do not hide essential information such as prices, warnings, or errors.
- Browsers without
namesupport just let several stay open, which is fine.
Tracking Toggles (Carefully)โ
The toggle event fires after a section opens or closes. Some sites use it to learn which FAQ questions are read most.
document.querySelectorAll("details").forEach((d) => {
d.addEventListener("toggle", () => {
if (d.open) console.log("opened:", d.id);
});
});
If you send this data anywhere, record aggregate counts, avoid personal data, and follow the privacy rules and consent requirements that apply where you operate. This is not legal advice.
When Not to Use detailsโ
| You need | A better fit |
|---|---|
| A menu or card that opens above the page and closes when you click away | Popover |
| A pop-up that blocks the page until answered | Dialog |
| A set of views where exactly one is always showing | Tabs, with the tab roles and keyboard handling |
| Site navigation with sub-menus | A button with aria-expanded that controls a list, which gives you full control of closing and keyboard use |
| Important content everyone must see | Plain content, in the open |
Checking Your Setupโ
- Submit a form that has an empty required field inside a closed section. Can the visitor tell what is wrong?
- Link to a question inside a nested section, and follow the link in a new tab.
- Use the keyboard: Tab to a summary, then press Enter or Space.
- Test with a screen reader if you can, and listen to the summary text and the open or closed state.
- Check the Network panel to see whether a closed section loads its heavy content.
- Turn on reduced motion in your system settings, and check that the animation stops.
- Look at the page in right-to-left text and at 200% zoom.
Best Practicesโ
- Keep required fields out of closed sections, or open the section on
invalid. - Give linkable sections an
id, and open their ancestors for deep links. - Write clear, short summaries, and keep links and buttons out of them.
- Keep nesting shallow.
- Use
loading="lazy"for heavy embeds inside closed sections. - Animate only as an enhancement, with a reduced-motion rule.
- Do not hide essential information.
- Choose a popover, dialog, or button when
detailsdoes not fit. - Track toggles only in aggregate, and respect privacy.
- Validate on the server.
Quick Checklistโ
- Required fields are visible, or their section opens on
invalid - Linkable sections have stable
ids, and ancestors open for deep links - Each summary is a short, clear label with no links or buttons inside
- Nesting is no more than two levels
- Heavy embeds inside are lazy
- Any animation respects
prefers-reduced-motion - Nothing essential is hidden
- I tested with the keyboard and at 200% zoom
Security and Privacy Notesโ
- Hidden is not secret. Content in a closed
detailsis in the page source and in the form. Never put private data or secrets there. See HTML Security Basics. - Build summaries and content safely. If visitor text is shown inside a section, set it with
textContent, notinnerHTML. See XSS Basics. - Third-party embeds in a section still carry risk. Use
sandbox,referrerpolicy, and a trusted source. See iFrame Security. - Toggle tracking is behaviour data. Collect as little as you need, and tell visitors what you collect.
Global Audience Notesโ
- Translated labels are longer. Let summaries wrap, and do not fix their width.
- Right-to-left languages move the marker to the other side. Use logical properties, such as
padding-inline-start, and test. - Touch targets matter on phones, where many visitors browse. Make summaries comfortable to tap.
- Slow connections benefit from lazy loading and from keeping long text collapsed until wanted.
- Write clear, plain questions, especially for FAQs read in a second language.
Common Mistakes to Avoidโ
- Hiding a required field in a closed section, and leaving visitors guessing.
- Putting links or buttons inside a summary.
- Expecting a deep link to open the right section in every browser.
- Nesting five levels deep.
- Writing vague summaries such as "More" or "Click here".
- Hiding essential information.
- Loading a heavy embed in a closed section without
loading="lazy". - Animating without a reduced-motion rule.
- Using
detailsfor a menu, and expecting it to close on outside clicks. - Putting secrets in hidden sections.
Practice Timeโ
- In the first tab, press Send with the phone empty and the section closed. What happens? Then tick the checkbox, reset, and try again.
- In the Deep Link Lab, click "Jump to Late refunds". Which sections open?
- Click "Close everything", then "Jump to Payments". What is different?
- Complete the True or False quiz.
- Add a required field inside a
detailson a test page, and add theinvalidlistener. - Write a
detailsfor a video embed withloading="lazy", and check the Network panel. - Rewrite three vague summaries from a page of yours as clear questions.
- Bonus: add the animation, then test it with reduced motion turned on.
Quick Recapโ
Click a question to check your answer.
1. Why can a closed details element break a form?
Its fields are still part of the form. A required field that is empty and hidden cannot show its message, so the form may refuse to send without the visitor seeing why.
2. How do you fix it?
Listen for the invalid event in the capture phase, and open the closest details of the failing field. Better still, keep required fields visible.
3. How do you make deep links reliable?
Give the target an id, and with a small script open every details around it, then scroll or focus to the target.
4. What belongs in a summary?
A short, clear label or question. Do not put links or buttons in it.
5. How can you avoid loading heavy content in a closed section?
Use loading="lazy" on images and frames inside it, and check the Network panel.
6. When is details not the right choice?
For menus that close on outside clicks, pop-ups that block the page, tabs, and important content. Use a popover, dialog, tabs, or plain content.
Key Takeawaysโ
- A closed
detailsstill belongs to the page and the form. - Open the section on
invalid, or keep required fields visible. - Open ancestors for deep links, and give linkable sections stable
ids. - Short, clear summaries, with no links or buttons inside.
- Animation and lazy loading are optional improvements.
- Pick the right tool: popover, dialog, tabs, or a plain element when
detailsdoes not fit. - Hidden is not secret.
Next up: Popover, where you will learn how the popover attribute opens menus, cards, and tooltips with no JavaScript, and closes them when the visitor clicks away.