如何实现响应式边距?解决两列堆叠后居中失效问题
修复响应式列堆叠后不居中的问题
你的问题出在小屏幕下,.column 设置了 width: 100% 却没去掉原本的左右 margin: 5%,加上 .row 本身的 margin: 5%,会让列的总宽度超出父容器,自然没法居中。下面给你两种实用修复方案:
方案一:用 Flexbox 布局(推荐)
Flexbox 能轻松实现响应式列排列和居中,代码更简洁易维护:
修改后的 CSS:
.row { margin: 5%; /* 开启flex布局,子元素横向排列 */ display: flex; /* 列之间留空白替代原margin */ gap: 10%; /* 小屏幕自动换行堆叠 */ flex-wrap: wrap; /* 子元素水平居中 */ justify-content: center; } .column { text-align: center; width: 40%; padding: 4%; border-radius: 20px; color: #f0e7e0; background: #777a44; margin-bottom: 10%; } /* 小屏幕适配 */ @media screen and (max-width: 600px) { .column { width: 100%; } }
HTML 保持不变(已翻译为中文):
<div class="row"> <div class="column"> <h2>有疑问?</h2> <br /> <p>文本内容</p> </div> <div class="column"> <h2>想联系我们?</h2> <br /> <p>文本内容</p> </div> </div>
方案二:调整原有布局的 margin 和宽度
如果不想用 Flexbox,直接修改原有 CSS 的小屏幕样式即可:
.row { margin: 5%; } .column { text-align: center; width: 40%; padding: 4%; border-radius: 20px; color: #f0e7e0; background: #777a44; margin-bottom: 10%; margin-left: 5%; margin-right: 5%; /* 让块级元素自身居中 */ display: block; margin-left: auto; margin-right: auto; } @media screen and (max-width: 600px) { .column { /* 计算宽度:100%减去左右margin总和,避免超出容器 */ width: calc(100% - 10%); /* 保留自动margin确保居中 */ margin-left: auto; margin-right: auto; } }
内容的提问来源于stack exchange,提问作者bree pav
相关产品推荐
相关产品推荐

