首页 > 解决方案 > 使用 flexbox 垂直对齐内容

问题描述

我正在创建一个图块,其中图像可以是图块的 50% 或图块的 75%,并且内容将填充剩余的区域/剩余空间。我的问题是我不想为图像设置特定高度,因为它会失去图像/纵横比。我有如下内容:

const tile= () => (
  <StyledWrapper>
    <StyledImageBlock>
      //get Image here
    </StyledImageBlock>
      <StyledTextContent>
        {getTitleOne()} //this is a span element
        {getTitleTwo()} //this is a span element
      </StyledTextContent>}
  </StyledWrapper>
);

在我的StyledWrapper我有以下内容:

  text-align: center;

  a {
    text-decoration: none;
  }

在我的StyledImageBlock我有以下内容:

  width: 100%;

在我的StyledTextContent我有以下内容:

align-content: center;
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;

但是项目拒绝垂直对齐,我为演示设置了高度,但StyledWrapper仍然height: 700px拒绝。我在哪里错了?关于如何实现我所描述的任何建议。

更多信息。在图像和内容上设置百分比高度时,我可以达到预期的结果,但是这样图像纵横比会变得更糟/拉伸我不想要的图像。最终,这个 tile 将进入一个 flexbox 网格。

标签: javascriptcssreactjsflexboxstyled-components

解决方案


You probably need to put

justify-content: center;
align-items: center;

on StyledWrapper. This will center the StyledImageBlock vertically and horizontally.


推荐阅读