Flex-box拉伸问题:如何为图片画廊盒子设置固定尺寸?
解决图片画廊盒子被拉伸的问题
我看你遇到的问题——画廊里的盒子被向下拉伸,没法保持固定尺寸,调整浏览器窗口后又恢复正常对吧?咱们来拆解下问题根源,然后给出修复方案。
问题分析
你的flex布局里有几个关键点导致了拉伸问题:
.box2设置了flex-grow:1,这会让它在水平方向占据容器的剩余空间,结合flex容器的默认行为,间接干扰了垂直方向的尺寸计算;- 没有给盒子设置
flex属性锁定尺寸,默认的flex-shrink:1会让盒子在容器空间不足时被压缩,空间充足时又可能被拉伸; box-sizing: content-box(在.scale类里)会让border额外增加盒子总尺寸,导致溢出容器,视觉上看起来像是被拉伸。
修复方案
我们只需要调整CSS部分,就能让盒子保持固定尺寸:
修改后的CSS代码
body{ height:90vh; background-image: radial-gradient( circle farthest-corner at 10% 20%, rgba(0,93,133,1) 0%, rgba(0,181,149,1) 90% ); background-repeat: no-repeat; animation: GradientAnimated 59s ease infinite; } .container{ margin-top: 10vh; display: flex; padding:-1px; width: 100vw; align-items: center; justify-content: space-around; } .container.inner{ margin-top:0; width: 50vw; height: 40vh; border: 2px solid black; align-items: center; justify-content: center; /* 避免盒子溢出容器换行 */ flex-wrap: nowrap; } .box{ box-sizing: border-box; /* 让border和padding算入盒子自身尺寸 */ flex: 0 0 15vw; /* 锁定尺寸:不拉伸、不收缩,基础宽度15vw */ height: 40vh; color: white; text-align: center; font-size: 4vw; } .box1{background-color:#f00;} .box2{background-color:#fa0;} /* 移除flex-grow,保持固定尺寸 */ .box3{background-color:#ff0;} .box4{background-color:#080;} .box5{background-color:#00f;} .box6{background-color:#6ae;} .box7{background-color:#90d;} .box8{background-color:#408;} .box.scale:hover{ cursor: pointer; } .cursor{ color: #222; } .cursor:hover{ cursor: pointer; animation: shake 1s cubic-bezier(.36,.07,.19,.97) both infinite; } .scale{ border: 2px solid black; animation-name: Scale; animation-timing-function:ease; animation-duration: 1s; animation-iteration-count:1; animation-fill-mode: forwards; } @keyframes Scale{ from{transform: scale(1);} to{transform: scale(1.5);} } @keyframes shake { 10%, 90% { transform: translate3d(-1px, 0, 0); } 20%, 80% { transform: translate3d(2px, 0, 0); } 30%, 50%, 70% { transform: translate3d(-4px, 0, 0); } 40%, 60% { transform: translate3d(4px, 0, 0); } } @keyframes GradientAnimated { 0%{background-position:0% 10%} 50%{background-position:100% 91%} 100%{background-position:0% 10%} }
关键修改点说明
flex: 0 0 15vw:这是核心,三个值分别控制flex-grow(不允许拉伸)、flex-shrink(不允许收缩)、flex-basis(基础宽度),让盒子严格保持你设置的尺寸,不受flex容器空间变化影响;box-sizing: border-box:确保盒子的border不会额外增加总尺寸,避免溢出容器导致的视觉拉伸;- 移除
.box2的flex-grow:1:如果需要某个盒子占据额外空间可以单独调整,但为了所有盒子保持固定尺寸,这个属性需要去掉; - 添加
flex-wrap: nowrap:确保盒子在容器内保持横向排列,不会因空间不足换行。
这样修改后,不管浏览器窗口怎么调整,盒子都会保持你设置的固定尺寸,不会再出现向下拉伸的问题啦。
内容的提问来源于stack exchange,提问作者Ahmed Gaafer
相关产品推荐
相关产品推荐

