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

标签 reactjs css 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%;
`;

最佳答案

您需要将 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/

相关文章:

html - 每行五个元素,带 flex,左对齐

javascript - 为什么这个 setState 意外地传递了旧值?

javascript - 使用自动完成的值填充状态( react )

css - 在网格区域中定位元素

jQuery 如果边框颜色和边框宽度 =

css - 为什么 flex 元素限制为父级大小?

reactjs - 在 Intl FormattedNumber 之前而不是之后使用货币符号来 react Intl FormattedNumber

reactjs - React 和 webpack 热加载器。 "waiting for roots to load...to reload the inspector"

css - 嵌套选择器内的&符号(父选择器)

html - Flexbox:包装后改变方向