You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:42:43