Flexbox居中布局桌面端正常 移动端第二行文本左对齐无法居中
问题原因
- flex容器设置的
align-items: center仅负责让<p>子元素整体在容器内水平居中,并没有规定<p>内部的文本对齐规则。移动端视口宽度不足时,第二句文本自动换行,换行后的内容默认左对齐,就会出现你看到的偏移效果。 - 嵌套在两个
<p>之间的<br>标签在flex纵向布局中属于多余节点,会产生不可控的额外间距,建议移除后用margin控制段落间距。
修复方案
不需要额外写媒体查询,只需给<p>标签统一加上文本居中规则即可,同时补充小优化避免其他布局问题:
<!DOCTYPE html> <html> <head> <title>Jefferson's Virginia</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> html, body{ height: 100%; margin: 0; /* 移除浏览器默认body边距,避免布局偏移 */ } body { background-color: #999; } .wrapper { height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; } p { font-family: "Times New Roman", Times, serif; font-size: 1.75em; font-weight: bold; text-align: center; /* 新增文本居中规则,即使换行内容也会居中展示 */ margin: 0 0 24px 0; /* 用margin控制段落间距,替换原来的br标签 */ } p.two { margin-bottom: 0; /* 最后一段取消底部多余间距 */ } </style> </head> <body> <div class="wrapper"> <p class="one"> Jefferson's Virginia Website </p> <p class="two"> In Process of Being Re-constructed </p> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Cor
相关产品推荐
相关产品推荐

