52

HTML5 adds two new elements that are useful for marking up a table of contents for an article: details and summary.

The details element defaults to closed (hides everything except the summary element) and when clicked, it expands to reveal its contents. When it does this, it adds an "open" attribute to the details element.

I would like the element to default to open without having to add the open attribute to the markup. Is it possible to do this via CSS or would scripting have to come into play?

Example:

<details>
<summary>Table of Contents</summary>
    <ul>
        <li><a href="#" class="active">Introduction</a></li>
        <li><a href="/2/">Body</a></li>
        <li><a href="/3/">Conclusion</a></li>
    </ul>
</details>
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
Scott B
  • 38,833
  • 65
  • 160
  • 266
  • never tried this, but maybe `details[open] { display: block; }`? – Marc B Jan 11 '13 at 20:53
  • 4
    Why don't you want to use the "open" attribute? – Toan Nguyen Feb 17 '14 at 11:46
  • 9
    @ToanNguyen in some cases (media queries) it may be useful to have the contents displayed by default. If a screen is flipped from horizontal to vertical, for example, you might want to force the contents open. – robrecord Jul 15 '20 at 10:29

4 Answers4

69

You can add the open attribute into the details tag like this:

<details open>
    <summary>Table of Contents</summary>
    <ul>
        <li><a href="#" class="active">Introduction</a></li>
        <li><a href="/2/">Body</a></li>
        <li><a href="/3/">Conclusion</a></li>
    </ul>
</details>

The details will then be expanded by default.

Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86
Ariona Rian
  • 9,153
  • 3
  • 24
  • 36
3

If you want a JS solution, you could give the details element an ID:

<details id="target-me">
 <summary>Table of Contents</summary>
  <ul>
    <li><a href="#" class="active">Introduction</a></li>
    <li><a href="/2/">Body</a></li>
    <li><a href="/3/">Conclusion</a></li>
  </ul>
</details>

And then use the following JS:

document.getElementById("target-me").open = true;
kosher
  • 335
  • 3
  • 13
2

If you want to do it in JavaScript

const details = document.querySelector("details");
details.setAttribute("open", "");

Related to html5 details tag open one by one javascript function working strange

aloisdg
  • 22,270
  • 6
  • 85
  • 105
0

You can also use the alternative below it still has the ability to open and close but initially, it's opened and you can test that (I provided the output from my computer):

<div>
    <h3>Open</h3>
    <details open>
        <summary>Always open</summary>
        Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
    </details>
</div>

check the photo of the output below:

Moez Ben Rebah
  • 170
  • 1
  • 12