Sub topic 3
Starting open or closed with the open attribute
This chapter covers the open attribute on <details>. It decides whether the widget starts expanded, and the browser keeps it in sync as the user interacts. You should already know the basic <details> and <summary> structure from the previous chapter, plus basic HTML, CSS selectors, and selecting elements in JavaScript. The attribute is simple, but several mistakes come up repeatedly: writing open="false", expecting a value to matter, and being surprised that script and user changes share one piece of state.
The working model
A <details> element has exactly two states: closed and open. The open attribute stores that state in the document itself.
- If the element has an
openattribute, it is open. The summary and the rest of the content are rendered. - If the element has no
openattribute, it is closed. Only the summary is rendered.
There is no hidden internal flag. The state of the widget is the presence or absence of an attribute in the DOM. This has three consequences that the rest of the chapter builds on.
- What you write in the HTML is the initial state.
- When the user opens or closes the widget, the browser adds or removes the attribute on the live element. You can see this in the browser's element inspector.
- Anything else that adds or removes the attribute, such as a script or a CSS-in-JS framework, changes the state in exactly the same way.
Boolean attributes
open is a boolean attribute. For these attributes, the value does not carry meaning. Only presence does. The HTML specification says that if the attribute is present, its value must be either the empty string or the attribute's own name (case-insensitive), with no surrounding whitespace. Browsers apply the same presence rule to any value.
| What you write | Result |
|---|---|
| `<details>` | Closed |
| `<details open>` | Open |
| `<details open="">` | Open |
| `<details open="open">` | Open |
| `<details open="false">` | Open (a common mistake) |
| `<details open="0">` | Open |
| `<details OPEN>` | Open (HTML attribute names are case-insensitive) |
The fifth row is the one that causes bugs. Developers who know frameworks such as React or Vue, where open={false} is understood and the attribute is omitted, sometimes carry that habit into plain HTML or into a template language that does not treat booleans specially. In plain HTML, open="false" means open. The only way to make the widget closed is to leave the attribute out.
The same rule applies in other boolean attributes you may have used, such as disabled, checked, and hidden.
Writing it in templates
If your HTML comes from a template engine, the template must emit the attribute conditionally, not emit it with a changing value. The exact syntax depends on the engine, but the shape is always "print the word open, or print nothing".
<!-- Wrong: always open, because the attribute is always present -->
<details open="{{ is_expanded }}">
<!-- Right: the attribute is printed only when the condition is true -->
<details {% if is_expanded %}open{% endif %}>Many engines and UI libraries have a dedicated boolean-attribute syntax that does this for you. Check how yours handles open before assuming it does.
Starting closed
A closed widget needs no open attribute at all. Because closed is the default, the shortest correct markup is the most basic form.
<details>
<summary>What is your return policy?</summary>
<p>You can return items within 30 days of delivery.</p>
</details>Use this form when the content is optional, long, or secondary. Typical examples are FAQ answers, advanced options in a settings panel, and technical details attached to an error message.
Starting open
Add the bare attribute to start expanded.
<details open>
<summary>Shipping information</summary>
<p>Orders ship within two business days.</p>
</details>The user can still collapse it by clicking the summary or pressing Enter or Space while the summary has focus. Starting open does not lock anything. It only chooses the first state the user sees.
Start open when most readers need the content and collapsing is a convenience. Typical examples are the first item of a documentation outline, or a sidebar section that should be visible until the reader decides otherwise. If you find that every <details> on a page starts open, the widget is probably not adding value, and plain headings and paragraphs may serve better.
What the browser does to the attribute
The browser treats the user's click as a request to flip the attribute. The sequence for a closed widget is:
- The user activates the summary.
- The browser adds
opento the<details>element. - The content becomes visible.
- A
toggleevent is queued for the element. Chapter 7 covers this event.
For an open widget, the steps are the same but the browser removes the attribute. You can verify this in a browser's developer tools. Open the elements panel, click the summary, and watch the attribute appear and disappear in the markup.
When the browser adds the attribute for you, it adds it with an empty value. So after a user click, element.getAttribute('open') returns the empty string, not "open" and not null. This matters if you ever write code like if (el.getAttribute('open')). An empty string is falsy in JavaScript, so that test is false even though the widget is open. Test with el.hasAttribute('open') instead, or use the open property, which is the subject of a later chapter.
const details = document.querySelector('details');
// After the user opens the widget by clicking:
console.log(details.getAttribute('open')); // "" (empty string, falsy)
console.log(details.hasAttribute('open')); // trueInitial state versus current state
The attribute you write in the HTML source is only the starting point. After the page loads, the live attribute reflects the user's most recent choice. Two situations show why this distinction matters.
First, if you inspect the element in your browser after clicking, the markup differs from your source file. This is expected, not a bug in your page.
Second, a page reload does not remember the choice. When the page is parsed again, the attribute comes from your source again, so every widget returns to its authored state. Browsers may restore form control values on reload, but they do not restore <details> state. If the user's choice must persist, you have to store it yourself, for example in localStorage, and reapply it with script.
Choosing the initial state with a script
Sometimes the right initial state depends on something the HTML author cannot know ahead of time, such as the viewport width. A filter panel may be better open on a wide desktop screen and closed on a phone. You can set the state once at load time by assigning the open property, which adds or removes the attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive initial state</title>
</head>
<body>
<details id="filters">
<summary>Filters</summary>
<ul>
<li>Price</li>
<li>Brand</li>
<li>Rating</li>
</ul>
</details>
<script>
const filters = document.querySelector('#filters');
const wide = window.matchMedia('(min-width: 48rem)');
// Run once at load: open on wide screens, closed on narrow ones.
filters.open = wide.matches;
</script>
</body>
</html>Three details of this example are worth noting.
- The
<script>comes after the<details>element, so the element exists when the script runs. - The script runs once. It does not listen for resize events. If it did, resizing the window would override the user's own choice, which is usually unwelcome.
- Without JavaScript, the widget stays closed, because the markup has no
open. That is a safe default: the content is still reachable by clicking.
Be aware of a visual side effect. If the script runs late, for example from a deferred file, a widget that is closed in the HTML may visibly jump open after the first paint. Keep the script small and place it right after the element, or render the correct state on the server when you can.
Styling the two states
Because the state lives in an attribute, CSS can select it with an attribute selector. This is the simplest way to style differently when the widget is open.
details {
border: 1px solid #ccc;
padding: 0.5rem 1rem;
}
details[open] {
background: #f8f8f8;
}
details[open] > summary {
font-weight: 700;
}The selector details[open] matches whenever the attribute is present, whatever its value. It matches open, open="", and open="false" alike, which is consistent with the browser's behavior. The next-but-one chapters on styling cover the marker and further techniques, so this chapter only introduces the idea that the open state is available to CSS.
Some current browsers also support a :open pseudo-class for this purpose. Check browser support before relying on it, and use details[open] where you need broad compatibility.
Nested widgets
Each <details> has its own independent open attribute. Opening a parent does not open its children, and closing a parent does not remove the attribute from its children. A child that was open when the parent was closed is still open when the parent is reopened.
<details open>
<summary>Account help</summary>
<details>
<summary>Passwords</summary>
<p>Use the reset link on the sign-in page.</p>
</details>
<details open>
<summary>Email</summary>
<p>Open account settings and edit the email field.</p>
</details>
</details>Here the outer widget and the "Email" widget start open, and "Passwords" starts closed. If the user closes "Account help" and reopens it, "Email" is still open. Deeply nested disclosure widgets get hard to scan, so use nesting sparingly.
Closed content is not always unreachable
A closed widget hides its content from view, but that does not mean the content is absent from the page. Some behaviors you may encounter:
- Browsers can include closed
<details>content in find-in-page. Several current browsers open the widget automatically when a match is found inside it. Support varies, so test in the browsers you target. - Navigating to a URL fragment that points at an element inside a closed
<details>can open the widget so the target is visible. The HTML specification describes this behavior. Again, confirm it in your target browsers. - Printing usually prints the page as it currently looks. Widgets that are closed stay closed on paper. If a printed version must show all content, you need a print-specific approach, such as starting those widgets open.
These behaviors are good reasons to keep important content discoverable and to avoid assuming that "closed" means "hidden from the user's search".
Common errors
- Writing
open="false". The widget is open, because the attribute is present. Remove the attribute instead. - Testing
getAttribute('open')for truthiness. After a user click the value is an empty string, which is falsy. UsehasAttribute('open'). - Expecting the state to survive a reload. The state resets to the authored markup. Store the choice yourself if it matters.
- Overriding the user's choice from a resize or timer handler. Set the initial state once, and leave later changes to the user.
- Starting everything open. If nothing is ever collapsed, the widget adds clicks without saving the reader any scrolling.
- Putting
openon<summary>. The attribute belongs on<details>. On any other element it has no effect for this widget.
Choosing the initial state
Use a short decision rule. Start closed when most readers can skip the content and the summary alone tells them whether they need it. Start open when most readers need the content and collapsing is optional. When you cannot decide, start closed and write a clear summary. The page then stays compact, and each summary acts as a label the reader can scan.
Exercise
A teammate writes <details open="false"><summary>Tips</summary><p>Save often.</p></details> and reports that the widget starts expanded. Explain why, then give two ways to make it start collapsed: one by editing the HTML and one with a single line of JavaScript, assuming the element has the id tips.
Show answer
open is a boolean attribute, so only its presence matters, not its value. The string "false" is just a value on a present attribute, so the widget is open. In HTML, remove the attribute entirely: <details>. In JavaScript, run document.querySelector('#tips').open = false;, or document.querySelector('#tips').removeAttribute('open');, either of which removes the attribute.
Exercise
A user opens a closed <details> by clicking its summary. What does el.getAttribute('open') return, and which check should you use to test whether the widget is open?
Show answer
It returns an empty string, because the browser adds the attribute with an empty value. An empty string is falsy in JavaScript, so a truthiness test on getAttribute('open') wrongly reports closed. Use el.hasAttribute('open'), or read the open property, which returns true or false.
Exercise
You have a page with a "Filters" widget that should start open on screens at least 48rem wide and closed on narrower screens. Write the HTML-plus-script approach in outline, and explain why you should not run the check inside a resize listener.
Show answer
Write the <details id="filters"> without open, then run a script after it that sets document.querySelector('#filters').open = window.matchMedia('(min-width: 48rem)').matches; once. A resize listener would reset the state every time the window size changed, overriding a choice the user made by clicking the summary. Setting it once at load picks a sensible starting state and then leaves control with the user.