如何让并排多个div在窗口缩小时整行一同换行而非逐个掉落
解决方案
问题本质
你当前遇到的问题核心是:视口宽度缩小过程中,会先达到「右侧50%宽度放不下3个价格盒子」的临界点,早于Bootstrap col-md-6 预设的响应式断点,所以会先出现价格盒逐个折行的情况,而非整列下移。
修改步骤
1. HTML调整
- 将两个
col-md-6的父容器替换为Bootstrap标准的row容器,避免栅格排版异常 - 删除右侧
.pricing-boxes所在div的行内display:inline-block属性,避免和CSS中定义的flex属性冲突
修改后对应HTML片段:
<div class="row" style="margin-left:3%"> <div class="col-md-6" style="color:white; float:left; margin-top:1%"> <div> <h2 style="color:white;"><b>Register by tommorow for the best rate!</b></h2> <p class="b2"> Special rates for teams of 3+ </p> </div> </div> <!-- 删除了行内的display:inline-block --> <div class="col-md-6 pricing-boxes"> <div class="pricing-box" style="margin-right: 10px; "><p style="font-size:50px"><b>$1495</b></p><p style="font-size:23px; margin-top:-30px">MEMBERS</p></div> <div class="pricing-box" style="margin-right: 10px; "><p style="font-size:50px"><b>$1495</b></p><p style="font-size:23px; margin-top:-30px">NON-MEMBERS</p></div> <div class="pricing-box"><p style="font-size:50px"><b>$2000</b></p><p style="font-size:23px; margin-top:-30px">VIPS</p></div> </div> </div>
2. CSS调整
- 给
.pricing-boxes添加禁止折行、最小宽度适配的属性,保证3个价格盒永远在同一行 - 新增自定义响应式断点,断点值 = 左侧文本区最小宽度 + 右侧3个价格盒总宽度,当视口宽度小于该值时直接让两列都占满整行
- 给
.pricing-box添加禁止压缩属性,避免盒子被挤变形
修改后完整CSS:
.register_container { background-color: #00205B; width: 80%; transform: translateX(12%); display: inline-block; margin: auto; margin-top: -175px; box-shadow: 5px 5px 5px #35353d; } .pricing-boxes { display: flex; flex-wrap: nowrap; /* 禁止内部盒子折行 */ min-width: fit-content; /* 容器最小宽度等于内容总宽度,不会被压缩 */ justify-content: flex-start; } .pricing-box { flex-shrink: 0; /* 禁止单个价格盒被压缩 */ background-color: white; padding-left: 15px; padding-right: 15px; margin-top: 7%; text-align: center; } /* 自定义断点,940px可根据你实际的内容总宽度调整 */ @media (max-width: 940px) { .register_container .col-md-6 { width: 100% !important; float: none !important; } /* 整列掉下去后如果想让价格盒居中可以加下面这行 */ /* .pricing-boxes { justify-content: center; } */ }
可选优化方案
如果不需要兼容老版本浏览器,也可以用CSS Grid实现该逻辑,代码会更简洁:给父容器设置grid-template-columns: repeat(auto-fit, minmax(最小宽度, 1fr)),把左侧的最小宽度设为文本区最小宽度,右侧的最小宽度设为3个价格盒的总宽度即可,自动触发整列换行。
内容的提问来源于stack exchange,提问作者Fliptavius
相关产品推荐
相关产品推荐

