【问题标题】:Justify-content: center breaks if child's content is wrapped onto more than 1 row with flex-wrap: wrap [duplicate]Justify-content:如果使用 flex-wrap 将孩子的内容包裹到多于 1 行,则居中中断:wrap [重复]
【发布时间】:2021-09-06 21:54:13
【问题描述】:

我有一个包含多个子元素的父 div 元素。父 div 包含在外部容器 div 中。我希望父 div 在容器内居中,但问题是父级使用 flex-wrap: wrap 包装其所有子 div。

父 div 按预期在容器中居中:

#container {
  width: 500px;
  display: flex;
  justify-content: center;
  background-color: #c0faff; 
}

#parent {
 display: flex;
 flex-wrap: wrap;
}

.child {
 background-color: #5bb4bb;
 width: 100px;
 height: 100px;
 margin: 5px;
}
<div id="container">
  <div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

但是,一旦有 1 个子元素必须包裹到第二行,父 div 就会向左浮动并忽略容器的 justify-content: center; css 属性:

#container {
  width: 500px;
  display: flex;
  justify-content: center;
  background-color: #c0faff; 
}

#parent {
 display: flex;
 flex-wrap: wrap;
}

.child {
 background-color: #5bb4bb;
 width: 100px;
 height: 100px;
 margin: 5px;
}
<div id="container">
  <div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>

如何让之前的代码sn-p的结果变成这样?:

【问题讨论】:

    标签: html css flexbox centering


    【解决方案1】:

    只有为容纳 flexbox-items 的容器设置固定宽度才能实现此目的。您可以让它更简单一点,并在此处的 CSS 中使用 calc(...) 函数。如果您知道一行应该有多少项目,您可以轻松更改多个断点的数量。如果您将一项的宽度设置为 css 自定义属性,则更容易。

    #container {
      width: 500px;
      display: flex;
      justify-content: center;
      background-color: #c0faff; 
    }
    
    #parent {
     display: flex;
     flex-wrap: wrap;
     width: calc(4* 110px)
    }
    
    .child {
     background-color: #5bb4bb;
     width: 100px;
     height: 100px;
     margin: 5px;
    }
    <div id="container">
      <div id="parent">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
      </div>
    </div>

    【讨论】:

    • 感谢@cloned,这对我的情况没有帮助,但它对某些人来说是一个解决方案,所以我会批准。我真的需要动态宽度才能工作,但看起来这样的解决方案在 flexbox 的约束下不存在。
    • 你可以在这里尝试使用网格。我想不出一个解决方案,但也许你会找到适合你的东西。
    猜你喜欢
    • 2021-08-27
    • 2020-11-23
    • 2017-12-03
    • 2017-01-28
    • 2023-04-04
    • 1970-01-01
    • 2018-09-16
    • 2013-07-15
    • 2021-03-26
    相关资源
    最近更新 更多