"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 Tags
An alternative and elegant solution lies in the HTML5 tags. The
element represents the toggleable header, while the
Example Code
Here's an example to demonstrate the usage of :
<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 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!