使用flexbox布局时header内H1标题无法居中问题求助
问题修复方案
核心问题根因
justify-content属于Flex容器专属属性,仅对设置了display: flex的元素生效,你当前给.header_text设置了justify-content: center但未开启Flex布局,该属性不会生效。- 父容器
.header为Flex布局时,子元素默认宽度由自身内容撑开,.header_text没有占满图片右侧的剩余空间,所以即便设置margin: 0 auto,也只是在.header_text自身的窄宽度内居中,视觉上会整体偏右。 - 你代码的HTML部分存在笔误:
<div class="header_text">前多写了一个<,会导致DOM结构渲染异常。
修复代码
你只需要修改.header、.header_img和.header_text的CSS样式即可:
.header { display: flex; flex-wrap: wrap; /* 新增:让子项垂直居中 */ align-items: center; height: 60vh; background-image: linear-gradient( to right bottom, rgba(12, 186, 186, 0.5), rgba(56, 0, 54, 0.5)), url(../img/code.jpg); background-size: cover; background-position: top; clip-path: polygon(0 0, 100% 0, 100% 55vh, 0 100%); color: #fff; padding: 40px; } /* 新增img容器宽度限制,避免图片太宽挤压文本区域,可根据需求调整数值 */ .header_img { width: 120px; flex-shrink: 0; } .header_img img { width: 100%; border-radius: 82%; padding: 0; } .header_text { /* 新增:占满剩余水平空间 */ flex: 1; /* 新增:内部文本水平居中 */ text-align: center; }
同时修正HTML的笔误:
<!-- 把原来的<<div改成<div --> <div class="header_text"> <h1>My Name</h1> <hr> <h2>Something Here</h2> </div>
效果说明
修改后.header_text会自动占满图片右侧所有剩余宽度,内部文本直接居中对齐,不需要额外设置margin。如果需要文本垂直方向也在.header_text内部居中,可以给.header_text加上display: flex; flex-direction: column; justify-content: center; height: 100%;即可。
内容的提问来源于stack exchange,提问作者Stephen Scott Moore
相关产品推荐
相关产品推荐

