利用max-height和transition实现CSS手风琴效果,通过隐藏复选框的:checked状态控制内容展开与收起,配合overflow:hidden完成平滑过渡动画,适用于FAQ等场景,无需JavaScript。
在CSS初级项目中实现手风 琴效果,可以利用 max-height 配合 transition 来控制内容的展开与收起。这种方法不需要JavaScript也能完成基础动效,适合用于FAQ、菜单折叠等场景。
直接对 height 使用 transition 对 auto 值无效,因为“auto”不是一个可计算的数值,无法进行平滑过渡。而 max-height 可以设置一个足够大的值(如 0 到 500px),通过改变它来模拟展开/收起效果。
这里是内容文本……
使用隐藏的复选框 结合 :checked 伪类来控制状态切换,label 作为可点击区域,触发显示/隐藏。
.accordion {
width: 100%;
margin-bottom: 10px;
}
.accordion input[type="checkbox"] {
display: none; / 隐藏输入框 /
}
.accordion label {
display: block;
background: #f0f0f0;
padding: 10px;
cursor: pointer;
border: 1px solid #ddd;
font-weight: bold;
}
.accordion .content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
background: #fff;
padding: 0 10px;
}
/ 展开状态:max-height 设为足够大 /
.accordion input[type="checkbox"]:checked ~ .content {
max-height: 500px; / 根据内容调整此值 /
}
当复选框被选中时,后续的 .content 元素的 max-height 从 0 过渡到 500px,实现展开动画;取消选中则恢复为 0,内容被隐藏。
替代 label,并结合 aria-expanded 提升可访问性。type="checkbox" 允许多个同时打开;若要单选,改用 type="radio"
并设置相同 name 属性即可。基本上就这些。这个方法简单有效,适合初学者掌握CSS过渡与状态控制的核心思路。不复杂但容易忽略细节,比如 overflow 和 transition 的配合使用。