Bootstrap Collapse 动画需手动添加 .collapse { transition: height 0.35s ease; },因默认无过渡;JS 动态设置像素高度配合该 CSS 实现平滑展开/收起,纯 CSS 方案可用 max-height 但需预设上限。

Bootstrap Collapse 类默认不带动画,得手动加 transition
Bootstrap 5 的 collapse 类本身只控制 display: none/block 和 height 的切换,但默认没有 CSS 过渡效果——所以展开/收起是瞬时的,看着生硬。动画得靠自己补 transition,而且必须作用在 .collapse 元素上,不能只写在 .show 里。
- 必须给
.collapse设置transition: height 0.35s ease(或all,但推荐只动height) - 同时要确保
height能被过渡:Bootstrap 用的是height: 0→height: auto,但auto无法过渡,所以它实际靠 JS 动态设内联style="height: XXXpx"来规避这个问题 - 如果你手动删了 JS 或用了纯 CSS 方案,就得换思路(比如用
max-height模拟)
直接复用 Bootstrap JS 时,CSS 只需补这一行
只要没禁用 Bootstrap 的 JS(bootstrap.bundle.min.js),就别自己重写展开逻辑。它的 JS 会在展开前读取内容高度、设为固定像素值,收起时再设回 0——这时你只需要让 height 可过渡即可。
.collapse {
transition: height 0.35s ease;
}
注意:不要加 !important,Bootstrap 默认 CSS 权重足够;也不用改 .collapsing 类(那是 JS 切换中的临时状态,已自带 height: 0)。
遇到「动画卡顿」或「收起后留白」多半是 padding/margin 干扰
CSS 过渡只管 height,但面板内容如果有大 padding、margin 或子元素用了 transform,视觉上就会感觉“没缩干净”或“抖一下”。常见干扰点:
立即学习“前端免费学习笔记(深入)”;
-
.collapse内部直接有padding-top/bottom:移到子容器上,或用overflow: hidden包一层 - 子元素用了
margin-bottom:改用padding-bottom或用:last-child清除 - 用了
border:border 会参与 height 计算,建议统一用box-sizing: border-box
不想依赖 JS?用 max-height 模拟(但有高度限制)
如果项目禁用了 Bootstrap JS,或者想纯 CSS 控制,可以用 max-height 替代 height。缺点是得预估最大高度(比如 max-height: 500px),否则动画会失真。
.collapse {
max-height: 0;
overflow: hidden;
transition: max-height 0.35s ease, opacity 0.35s ease;
}
.collapse.show {
max-height: 500px;
opacity: 1;
}
这个方案没法精确适配任意高度内容,500px 是经验值;若内容超长,收起时会突然截断;若太小,动画时间会偏长。真要通用,还是得靠 JS 测高。
Bootstrap 的 collapse 动画关键不在 JS 多聪明,而在 CSS 是否接管了 height 的渐变过程——漏掉那一行transition,其他都白搭。










