我试图垂直对齐两组行,每一行的一侧包含图像,另一侧包含文本。尽管我有通过使用下面的代码使用 flex 垂直对齐的经验,但在这种特殊情况下我似乎必须使用不同的东西:
justify-content: center;
flex-direction: column;
text-align: center;
这就是我想要实现的(注意红框是图片,灰框是文字):
但是,我遇到了以下情况,文本不是垂直居中而是与图像顶部对齐:
这是 DOM 结构的样子 (ReactJS):
<LandingPinkDiv>
<Grid container spacing={24}>
<Grid item xs={12}>
<LandingTitleWhite>Title</LandingTitleWhite>
</Grid>
<LandingRowDiv>
<Grid item xs={6}>
<LandingImageDiv>
<LandingImage
src={1}
width="320px"
height="304px"
/>
</LandingImageDiv>
</Grid>
<Grid item xs={6}>
<LandingTextContainer>
<LandingSubheadingWhite>
Subheading
</LandingSubheadingWhite>
<LandingSubtitleBlack>
SubTitle
</LandingSubtitleBlack>
</LandingTextContainer>
</Grid>
</LandingRowDiv>
<LandingRowDiv>
<Grid item xs={6}>
<LandingTextContainer>
<LandingSubheadingWhite>
SubHeading
</LandingSubheadingWhite>
<LandingSubtitleBlack>
Subtitle
</LandingSubtitleBlack>
</LandingTextContainer>
</Grid>
<Grid item xs={6}>
<LandingImageDiv>
<LandingImage
src={2}
width="320px"
height="197px"
/>
</LandingImageDiv>
</Grid>
</LandingRowDiv>
</Grid>
</LandingPinkDiv>
对应的 CSS 是这样的:
export const LandingRowDiv = styled.div`
display: flex;
/* justify-content: center;
flex-direction: column;
text-align: center; */
margin-bottom: 10%;
padding-left: 10%;
padding-right: 10%;
`;
export const LandingPinkDiv = styled.div`
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
height: 170vh;
background: #e72564 !important;
`;
export const LandingTextContainer = styled.div`
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
margin-right: 10%;
`;
最佳答案
您需要将 align-items: center
添加到您的 LandingRowDiv
样式组件中:
export const LandingRowDiv = styled.div`
align-items: center;
display: flex;
justify-content: center;
flex-direction: row;
text-align: center
margin-bottom: 10%;
padding-left: 10%;
padding-right: 10%;
`;
关于reactjs - 使用 Flexbox 垂直对齐和居中多个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799650/