如何用纯CSS实现DOM子元素移除时DIV的height过渡动画?
纯CSS实现子元素移除时容器高度过渡动画
当然有纯CSS的解决方案啦!不过得先搞清楚为什么直接用transition: height不行——因为CSS过渡需要明确的起始和结束数值,而height: auto是浏览器根据内容动态计算的,它没法在两个auto值之间生成平滑的过渡动画。下面给你两种实用的纯CSS方案:
方案一:利用max-height模拟过渡(最常用)
这个技巧的核心是用max-height代替height来做过渡,结合:has()伪类检测子元素的存在状态,让容器高度平滑变化。
示例代码
<div id="master"> <div id="child1">some content<br>some more content<br>even more content</div> <div id="child2">some other content</div> </div> <button onclick="document.getElementById('child1').remove()">移除child1</button>
#master { max-height: 500px; /* 设置一个足够容纳所有内容的最大值 */ transition: max-height 0.5s ease-out; overflow: hidden; border: 1px solid #ddd; padding: 10px; } /* 当child1被移除后,把max-height设置为仅容纳child2的高度 */ #master:not(:has(#child1)) { max-height: 80px; /* 根据child2的实际高度调整 */ }
注意:你需要预估容器的最大可能高度和子元素移除后的高度,如果内容高度不确定,可以把最大值设得足够大(比如1000px),只要不影响页面布局就行。
方案二:利用CSS Grid的行高过渡
如果你明确知道子元素的数量,可以用CSS Grid来控制每行的高度,通过过渡grid-template-rows实现平滑效果。
示例代码
#master { display: grid; grid-template-rows: auto auto; /* 两行分别对应child1和child2 */ transition: grid-template-rows 0.3s ease; overflow: hidden; border: 1px solid #ddd; padding: 10px; } /* 移除child1后,第一行高度过渡为0 */ #master:not(:has(#child1)) { grid-template-rows: 0 auto; } /* 额外处理child1的边距和内边距,避免残留空间 */ #child1 { margin: 10px 0; transition: margin 0.3s ease, padding 0.3s ease; } #master:not(:has(#child1)) #child1 { margin: 0; padding: 0; height: 0; overflow: hidden; }
浏览器兼容性
这两个方案都依赖CSS的:has()伪类,它目前在Chrome、Firefox 121+、Safari 15.4+等现代浏览器中都得到了支持,如果你的项目不需要兼容旧版浏览器,完全可以放心使用。
内容的提问来源于stack exchange,提问作者astralmaster
相关产品推荐
相关产品推荐

