乐闻世界logo
搜索文章和话题

How do you implement a CSS-only "accordion" effect without JavaScript?

1个答案

1

Without JavaScript, we can implement an accordion effect using pure CSS. This primarily relies on the CSS :checked pseudo-class and HTML <input type="radio"> or <input type="checkbox"> elements. Here is a step-by-step implementation and example:

Step 1: HTML Structure

First, we need to set up the correct HTML structure. For this example, we use <input type="checkbox"> because it allows multiple sections to be expanded simultaneously (if you prefer only one section to be expanded at a time, use <input type="radio"> and ensure the inputs share the same name attribute).

html
<div class="accordion"> <input type="checkbox" id="section1"> <label for="section1">Section 1</label> <div class="content"> Content for Section 1 </div> <input type="checkbox" id="section2"> <label for="section2">Section 2</label> <div class="content"> Content for Section 2 </div> <input type="checkbox" id="section3"> <label for="section3">Section 3</label> <div class="content"> Content for Section 3 </div> </div>

Step 2: CSS Styles

Next, we need to add CSS to hide the content and make it visible when the relevant input is selected.

css
/* Basic styles */ .accordion { width: 300px; border: 1px solid #ccc; } .content { max-height: 0; overflow: hidden; transition: max-height 0.3s ease; } /* Using the :checked pseudo-class */ input[type="checkbox"] { display: none; } input[type="checkbox"]:checked + label + .content { max-height: 100px; } label { display: block; padding: 10px; background: #eee; border-bottom: 1px solid #ccc; cursor: pointer; }

In this CSS, .content is initially hidden (max-height: 0;), and when the adjacent <input> is checked, .content's max-height is set to a value sufficient to display the content (e.g., 100px). This causes the content to smoothly expand due to the CSS transition effect.

Example Effect

In this example, clicking a label will expand or collapse the corresponding content section. This effect requires no JavaScript; it can be implemented using only CSS and simple HTML, making it ideal for simple interactive effects.

The advantage of this method is its simplicity and independence from JavaScript, allowing it to work in environments where JavaScript is disabled. Additionally, it provides good compatibility and performance.

2024年8月7日 18:04 回复

你的答案