React项目使用flex属性居中内容失效,文字错位问题如何解决
问题原因
- 百分比高度失效:你给
imageContianer设置了height: 60%,但它的父元素content没有明确的高度值,浏览器无法计算百分比高度,导致整个容器高度计算错乱,才会出现「Who am I」文本跑到上层容器的问题。 - React Bootstrap 布局属性缺失:
Row和Col默认没有内置居中样式,你没有给网格容器添加对齐配置,蓝色标注区域自然无法居中。
修复代码
import { Col, Row } from 'react-bootstrap'; const content=css` display: flex; flex-direction: column; justify-content: center; align-items: center; /* 给外层容器设置明确高度,这里示例为占满视口高度,可根据实际父容器调整 */ min-height: 100vh; width: 100%; /* 控制标题和下方内容的间距 */ gap: 24px; `; // 修正拼写错误(之前是imageContianer) const imageContainer=css` width: 100%; max-width: 700px; /* 移除无效的百分比高度,改用最小高度限制 */ min-height: 300px; display: flex; align-items: center; justify-content: center; `; const About =()=>{ return ( <div css={content}> <p>Who am I ?</p> <div css={imageContainer}> {/* 添加bootstrap内置对齐类:整行宽度100%、内容垂直居中、水平居中、文本居中 */} <Row className="w-100 align-items-center justify-content-center text-center"> <Col md="auto"> <img src={ Icon } width='200' height='180' alt='Icon' /> </Col> <Col md="auto"> <p>First</p> <p>Second</p> <p>Third</p> </Col> </Row> </div> </div> ); }
补充说明
如果外层还有父容器,把content的min-height:100vh改成height:100%即可,要保证所有上层父元素都有明确高度,百分比高度才会生效。
内容的提问来源于stack exchange,提问作者sojinLee
相关产品推荐
相关产品推荐

