
本文详解如何通过 css `height` 和 `overflow: hidden` 配合 `transition` 实现真正的可折叠容器展开 / 收起动画,避开 `display: none` 导致过渡失效的常见误区,并提供简洁可靠的 html/css/js 实现方案。
CSS 的 transition 属性 无法在 display: none 与 display: block(或其他值)之间产生过渡效果 ——因为 display 是一个离散的、非连续的属性, 浏览器 无法计算“半隐藏”状态,因此任何涉及 display 切换的动画都会表现为突兀的跳变。
要实现 Obsidian 风格的平滑折叠动画,核心原则是:仅对可插值的连续属性(如 height、opacity、max-height)应用过渡,并配合 overflow: hidden 截断溢出内容。
✅ 正确做法:用 height + overflow: hidden 替代 display
以下是一个精简、可复用的实现示例:
Click To Open I am Text! In fact I am so much text that I make the Foldable Container Div Larger!
.container {padding: 50px; width: 200px; background: #affaf7;} #foldable-content {background-color: #8fbdbb; transition: height 0.4s cubic-bezier(0.02, 0.01, 0.47, 1); overflow: hidden; height: 0; padding: 0 10px; } .container.open #foldable-content {height: auto; /* 注意:height: auto 本身不可过渡 → 需预先设定固定高度或改用 max-height */}
const toggle = document.getElementById('toggle'); const container = document.querySelector('.container'); toggle.addEventListener('click', () => {container.classList.toggle('open'); });
⚠️ 关键注意事项:
- height: auto 不能参与 CSS 过渡。若需动态适配内容高度,推荐两种稳健方案:
- 使用 max-height 过渡(更通用,适合未知高度):
#foldable-content {max-height: 0; overflow: hidden; transition: max-height 0.4s ease-out, padding 0.4s ease-out;} .container.open #foldable-content {max-height: 500px; /* 设为足够容纳全部内容的上限值 */ padding: 10px;} - JavaScript 动态计算并设置 height(最精准,但需重排):
toggle.addEventListener('click', () => {const content = document.getElementById('foldable-content'); if (container.classList.contains('open')) {content.style.height = '0'; // 等过渡结束再设为 none(可选)setTimeout(() => content.style.display = 'none', 400); } else {content.style.display = 'block'; content.style.height = '0'; // 强制重排,触发 height 计算 void content.offsetHeight; content.style.height = `${content.scrollHeight}px`; } container.classList.toggle('open'); });
- 使用 max-height 过渡(更通用,适合未知高度):
✅ 推荐组合(兼顾简洁与健壮):
- 使用 max-height + 合理上限值(如 600px),适用于大多数文档类折叠需求;
- 配合 cubic-bezier(0.02, 0.01, 0.47, 1) 这类缓入缓出曲线,模拟自然弹性感;
- 始终设置 overflow: hidden,确保内容不溢出过渡区域。
最终效果将完全复现 Obsidian Callouts 的流畅体验:点击标题,内容区域以平滑动画展开或收起,无闪烁、无跳变,且兼容 响应式布局。






























