CSS过渡问题:max-width元素无法过渡展开的解决方法
问题描述
我做了两个示例:
- 第一个元素固定
width为400px,能通过transition实现展开效果; - 第二个元素设置
max-width为400px、width为100%,无法实现过渡展开。
但过渡前检测offsetWidth时,两者的返回值都是400。请问怎么让第二个元素实现过渡展开?
原代码示例
HTML
<div class="plan"></div> <a href="#" id="t">expand</a> <div class="plan2"></div> <a href="#" id="t2">expand 2</a>
CSS
.plan { width: 400px; position: relative; top: 0; left: 0; transition: width 0.3s ease-out, height 0.3s ease-out; height: 100px; background: red; } .plan2 { max-width: 400px; width: 100%; position: relative; top: 0; left: 0; transition: width 0.3s ease-out, height 0.3s ease-out; height: 100px; background: red; } .expanded { width: 100%; max-width: none; }
JavaScript
document.getElementById('t').addEventListener('click', function() { console.log(document.querySelector('.plan').offsetWidth) document.querySelector('.plan').classList.add('expanded') }) document.getElementById('t2').addEventListener('click', function() { console.log(document.querySelector('.plan').offsetWidth) document.querySelector('.plan2').classList.add('expanded') })
解决方案
问题核心在于第二个元素的过渡逻辑错误:
.plan2初始width已经是100%,添加expanded类后width没有数值变化,所以transition: width完全不起作用;- 你修改了
max-width但没给它加过渡效果,自然看不到平滑动画。
调整方案如下:
修改后的CSS
.plan2 { max-width: 400px; width: 100%; position: relative; top: 0; left: 0; /* 给max-width添加过渡,去掉没用的width过渡 */ transition: max-width 0.3s ease-out, height 0.3s ease-out; height: 100px; background: red; } .expanded { /* 不需要修改width,把max-width设为足够大的值即可 */ max-width: 100vw; /* 或者根据父容器宽度设为100% */ }
修正后的JavaScript
document.getElementById('t').addEventListener('click', function() { console.log(document.querySelector('.plan').offsetWidth) document.querySelector('.plan').classList.add('expanded') }) document.getElementById('t2').addEventListener('click', function() { // 修正为打印第二个元素的宽度 console.log(document.querySelector('.plan2').offsetWidth) document.querySelector('.plan2').classList.add('expanded') })
原理说明
- 初始状态下,
.plan2的width:100%被max-width:400px限制,实际宽度是400px; - 添加
expanded类后,max-width变为100vw(或父容器宽度),width:100%会自动占满可用空间; - 因为给
max-width加了过渡效果,所以宽度变化会平滑展示出来。
内容的提问来源于stack exchange,提问作者Toniq
相关产品推荐
相关产品推荐

