如何使用HTML+CSS Flexbox实现多屏响应式布局并修复现有代码问题
Flexbox响应式布局修改方案
存在的问题
- 全局父容器设置了固定高度,小屏、中屏子元素换行后高度不足导致内容溢出
- 中屏断点下父容器未设置均匀分布规则,两列布局子元素排版错位
- 中屏媒体查询未设置最大宽度,规则优先级存在冲突隐患
- 子元素内部文本无间距,排版拥挤
- 换行后最后一行子元素底部多余空白未清除
- 未设置盒模型规则,宽度计算可能出现溢出偏差
完整修改后代码
HTML代码
<div class="parent"> <div class="child"><span>Product one</span>This Is Product</div> <div class="child"><span>Product two</span>This Is Product</div> <div class="child"><span>Product three</span>This Is Product</div> <div class="child"><span>Product four</span>This Is Product</div> </div>
CSS代码
/* 全局公共样式 */ * { box-sizing: border-box; margin: 0; padding: 0; } span { font-weight: bold; margin-right: 8px; } .parent { display: flex; width: 100%; background-color: #fff; align-items: center; } .child { display: flex; height: 71px; background-color: #eee; align-items: center; justify-content: center; } /* 小屏:<992px */ @media (max-width: 991px) { span { color: #000; } .parent { flex-wrap: wrap; justify-content: space-around; } .child { width: 100%; margin-bottom: 10px; } .child:last-child { margin-bottom: 0; } } /* 中屏:992px-1199px */ @media (min-width: 992px) and (max-width: 1199px) { span { color: red; } .parent { flex-wrap: wrap; justify-content: space-around; } .child { width: 45%; margin-bottom: 15px; } .child:nth-last-child(-n+2) { margin-bottom: 0; } } /* 大屏:≥1200px */ @media (min-width: 1200px) { span { color: aqua; } .parent { height: 100px; justify-content: space-around; } .child { width: 18%; } }
核心修改说明
- 明确了三个断点的生效范围,避免样式冲突
- 父容器固定高度仅在大屏下生效,中小屏高度自适应适配换行内容
- 补充了盒模型规则,避免宽高计算偏差
- 中屏下增加均匀分布规则,保证两列布局左右间距一致
- 优化了子元素内部文本间距,清除了末尾多余的底部空白
- 合并了重复的公共样式,减少冗余代码
内容的提问来源于stack exchange,提问作者fadi safou
相关产品推荐
相关产品推荐

