使用max-height是实现表格行高过渡最实用的方法,通过设置max-height过渡并配合overflow:hidden,可在hover或点击时模拟内容展开动画,解决tr无法直接过渡height的问题。

在CSS中使用 transition 制作表格行高过渡,关键在于对 height 属性设置平滑动画。虽然表格行(tr)本身不支持直接的 height 过渡(因为 tr 的高度是内容决定的),但我们可以通过一些技巧实现视觉上的行高过渡效果。
推荐做法是在 td 内部使用一个块级元素(如 div),并控制该元素的高度和过渡。
<table>
<tr class="expandable">
<td>
<div class="content">这是一行可展开的内容</div>
</td>
</tr>
</table>
CSS 设置如下:
.content {
height: 0;
overflow: hidden;
transition: height 0.3s ease;
}
<p>.expandable:hover .content {
height: 40px; /<em> 根据实际内容调整 </em>/
}</p>由于无法对 auto 高度做过渡,可用 max-height 模拟。
立即学习“前端免费学习笔记(深入)”;
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}
<p>.expandable:hover .content {
max-height: 100px; /<em> 设置足够大的值以容纳内容 </em>/
}</p>这种方式适合内容高度不确定的情况,只要 max-height 大于实际内容高度即可。
若需要点击切换,可用 JS 添加或移除类名:
document.querySelector('.expandable').addEventListener('click', function() {
this.classList.toggle('expanded');
});
对应 CSS:
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}
<p>.expanded .content {
max-height: 100px;
}</p>基本上就这些方法。使用 max-height 是最实用的方案,能避开表格布局限制,实现自然的行高展开收起效果。
以上就是在css中如何用transition制作表格行高过渡的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号