如何用CSS实现网格行随内容变化自动调整高度的动画?
实现网格自动行高的过渡动画
在使用grid-template-rows: auto 1fr的布局中,直接给网格行的auto高度添加过渡动画无法生效——网格布局的行高计算逻辑不支持对auto值做过渡。要实现内容变化时的高度动画,无需修改网格的行设置,只需要在#top元素内部做处理:
解决方案思路
利用max-height属性的过渡效果模拟高度变化:给#top设置overflow: hidden,通过切换max-height的值触发动画,网格的auto行会自动跟随子元素的高度变化,无需改动grid-template-rows。
完整代码示例
CSS 样式
body { margin: 0; /* 清除默认边距 */ } #grid { display: grid; height: 100vh; /* 占满视口高度,方便演示 */ grid-template-rows: auto 1fr; gap: 1rem; /* 可选,添加行间距提升可读性 */ padding: 1rem; box-sizing: border-box; } #top { overflow: hidden; max-height: 60px; /* 初始内容对应的高度,可根据实际情况调整 */ transition: max-height 0.3s ease; /* 0.3s过渡时长,ease缓动效果 */ background-color: #f5f5f5; padding: 0.5rem; } /* 内容扩展时的状态类 */ #top.content-expanded { max-height: 500px; /* 设置一个足够容纳最大内容的高度 */ } #bottom { background-color: #e0e0e0; padding: 0.5rem; }
HTML 结构
<div id="grid"> <div id="top"> <p>Top content</p> <button onclick="toggleContent()">切换内容</button> </div> <div id="bottom">Bottom content</div> </div>
JavaScript 逻辑(模拟内容变化)
let contentAdded = false; function toggleContent() { const topEl = document.getElementById('top'); if (!contentAdded) { // 添加内容,触发高度变化 topEl.innerHTML += ` <p>新增内容行 1</p> <p>新增内容行 2</p> <p>新增内容行 3</p> `; topEl.classList.add('content-expanded'); } else { // 恢复初始内容 topEl.innerHTML = `<p>Top content</p><button onclick="toggleContent()">切换内容</button>`; topEl.classList.remove('content-expanded'); } contentAdded = !contentAdded; }
关键注意事项
max-height的目标值要设置得足够大,确保能容纳所有可能的内容,避免内容被截断;- 如果初始内容高度不确定,可以通过JS计算
#top的scrollHeight,动态设置初始max-height; - 过渡时长和缓动函数可以根据需求调整,比如
0.5s linear会让动画更匀速。
内容的提问来源于stack exchange,提问作者qscott86
相关产品推荐
相关产品推荐

