Home  >  Article  >  Web Front-end  >  How to Create Collapsible Divs with HTML5 `` and ``?

How to Create Collapsible Divs with HTML5 `` and ``?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 02:56:02468browse

How to Create Collapsible Divs with HTML5 `` and ``?

"How to create collapsible divs using HTML and CSS"

Collapsible divs are commonly used to present dynamic and organized content on a web page. Typically, these divs contain a header and a hidden body that can be expanded and collapsed on user interaction. Creating collapsible divs solely with CSS can be convenient, especially for maintaining a clean and straightforward codebase.

The :target Pseudo-Class

Earlier approaches to CSS collapsible divs involved utilizing the :target pseudo-class, which activates styles when a specific element is linked by a target attribute (e.g., ). However, this technique requires substantial repetition for multiple collapsible elements, resulting in a bloated CSS code.

The HTML5

and Tags

An alternative and elegant solution lies in the HTML5

and tags. The element represents the toggleable header, while the
element encapsulates the collapsible content. This approach eliminates the need for custom JavaScript or complex CSS, significantly simplifying the process of creating collapsible divs.

Example Code

Here's an example to demonstrate the usage of

and :

<code class="html"><details>
  <summary>This is the collapsible header</summary>
  <div class="content">This is the collapsible body</div>
</details></code>

Browser Compatibility

While the

and tags offer a convenient solution, browser compatibility must be considered. They are supported in modern browsers, including Chrome, Firefox, and Safari; however, not all browsers may render it with the same behavior.

For wide browser support, if necessary, you can use a polyfill like details-polyfill.

The above is the detailed content of How to Create Collapsible Divs with HTML5 `` and ``?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn