使用white-space: nowrap后标题无法居中的问题求助
解决标题无法居中的问题
你的问题出在这两点:
display: inline-block让标题元素的宽度仅由内容决定,且justify-content: center是flex容器的属性,直接给标题加这个属性完全无效- 没有设置正确的居中对齐规则,导致标题没有真正居中
方案一:给父容器添加文本居中样式
利用 inline-block 元素受父容器 text-align 属性影响的特性,修改代码如下:
.about-top { text-align: center; /* 让父容器内的行内/行内块元素居中 */ } .section-title { font-size: 4rem; font-weight: 300; color: black; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.2rem; clear: both; display: inline-block; white-space: nowrap; /* 保留单行设置 */ /* 移除无用的 justify-content: center 和 overflow: hidden */ }
方案二:将标题改为块级元素并设置文本居中
把标题的 display 改为 block,直接通过 text-align: center 让内部文本居中,同时保留单行效果:
.section-title { font-size: 4rem; font-weight: 300; color: black; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.2rem; clear: both; display: block; /* 改为块级元素 */ white-space: nowrap; /* 防止换行 */ text-align: center; /* 文本居中 */ /* 移除无用的 justify-content: center 和 overflow: hidden */ }
两种方案都能实现你要的「整体居中+单行显示」效果,选哪种看你布局的其他需求。
内容的提问来源于stack exchange,提问作者Alex JB
相关产品推荐
相关产品推荐

