不使用Grid如何用CSS实现指定布局并解决盒子换行对齐问题
解法1:使用Flex布局(无需Grid,兼容性好)
你当前的问题根源是float: right的特性:容器宽度不足时右浮动元素换行后仍会保持右对齐逻辑,不会自动靠左。改用flex布局可以轻松实现需求,修改后的CSS代码如下:
.order-confirmation { .confirmation-body-area { width: 90%; margin: auto; display: flex; flex-wrap: wrap; /* 允许元素换行 */ justify-content: space-between; /* 宽屏时两个元素左右贴边对齐 */ .box { /* 删掉原有的inline-block和float相关样式即可 */ } .box-1 { background: red; height: 214px; width: 631px; } .box-2 { background: blue; height: 214px; width: 427px; } .box-3 { background: yellow; height: 214px; width: 631px; } } }
宽屏状态下box1居左、box2居右排列,容器宽度小于两个盒子总宽度(1058px)时,box2会自动换行到第二行的行首位置,完全符合预期效果。
解法2:保留浮动逻辑,新增媒体查询适配
如果你不想改动原有浮动的写法,只需要增加断点媒体查询即可:
.order-confirmation { .confirmation-body-area { width: 90%; margin: auto; .box { display: inline-block; } .box-1 { background: red; height: 214px; width: 631px; float: left; } .box-2 { background: blue; height: 214px; width: 427px; float: right; } .box-3 { background: yellow; height: 214px; width: 631px; clear: both; } /* 新增媒体查询,宽度小于两个盒子总宽度时修改box2的浮动方向 */ @media (max-width: 1058px) { .box-2 { float: left; } } } }
当屏幕宽度小于1058px时,box2自动改为左浮动,换行后就会对齐到行首位置。
内容的提问来源于stack exchange,提问作者Tanvir Rahman
相关产品推荐
相关产品推荐

