【问题标题】:Why isn't my flex item aligning in the center?为什么我的弹性项目没有在中心对齐?
【发布时间】:2017-04-08 04:16:11
【问题描述】:

我正在尝试在页面中间居中放置一个红色框。

我已将 flex 容器的高度设置为 100%,并将 html,body 设置为 100%,但它仍然没有对齐中心。

谁能帮我理解为什么它不起作用?谢谢!

html, body {
  height: 100%;
}
.flex-container {
  display: flex;
  flex-flow: column;
  justify-content: center;
  height: 100%;
}
.box {
  flex: 0 0 100px;
  background: red;
  width: 100px;
}
<div class='flex-container'>
    <div class='box'></div>
</div>

【问题讨论】:

    标签: html css flexbox centering


    【解决方案1】:

    您使用justify-content主轴上对齐弹性项目。

    您使用align-items交叉轴上对齐弹性项目。

    因为你的弹性容器是flex-direction: column:

    • 主轴是垂直的,并且
    • 横轴是水平的。

    justify-content: center 工作正常。

    您只需添加align-items: center

    html, body {
      height: 100%;
    }
    .flex-container {
      display: flex;
      flex-flow: column;
      justify-content: center;       /* centers flex items vertically, in this case */
      align-items: center; /* NEW */ /* centers flex items horizontally, in this case */
      height: 100%
    }
    .box {
      flex: 0 0 100px;
      background: red;
      width: 100px;
    }
    <div class='flex-container'>
      <div class='box'></div>
    </div>

    这里有更详细的解释:

    【讨论】:

      【解决方案2】:

      您需要将 align-items 添加到 .flex-container

      align-items: center;
      

      请参阅此处以获取示例 https://jsfiddle.net/x9gyheo6/1/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-22
        • 1970-01-01
        • 2022-12-21
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多