使用Flexbox垂直对齐和居中多个div

时间:2018-06-11 14:05:54

标签: css reactjs css3 flexbox material-ui

我正在尝试垂直对齐两组行,每行包含一侧的图像和另一侧的文本。虽然我有使用flex通过使用下面的代码垂直对齐的经验,但在这种特殊情况下我似乎需要使用不同的东西:

  justify-content: center;
  flex-direction: column;
  text-align: center;

这就是我想要实现的目标(请注意,红色框是图像,而灰色框是文本):

enter image description here

但是,我得到的情况如下,文字没有垂直居中但与图像顶部对齐:

enter image description here

这就是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%;
`;

3 个答案:

答案 0 :(得分:1)

您需要将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%;
`;

答案 1 :(得分:0)

您应该在LandingRowDiv&#39;中使用align-items: center;。风格的组分。

答案 2 :(得分:0)

不确定我是否正确但您可以考虑以下html

figure {
    display: flex;
    width: 100%;
}

figure img {
    width: 50%;
}

figure figcaption {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
}

然后是以下css

=IF(COUNT(A3:C3); MIN(A3:C3; 2); "")

(你可以在p上使用align-self而不是align-items)