如何在 flex 容器中居中对齐 div 网格?

2022-01-18 00:00:00 grid alignment html css center

我正在尝试将放置在 flex-container div<中的 3 列网格(由 6 个 flex-items 组成)居中对齐/代码>.(参考附图)

I am trying to centre align the 3 column grid (which is made up of 6 flex- items) placed in a flex-container div. (Refer to image attached)

我厌倦了 floatalign-content 的许多变体.我还尝试将弹性项目放在子容器中,但无法使其工作.

I tired many variations of float and align-content. I also tried to place the flex items in a sub container but couldn't make it work.

这是我目前拥有的:

.flex-container {
  flex-direction: row;
  display: -webkit-flex;
  display: inline-flex;
  background-color: #f5f7f9;
  width: 100%;
  align-content: center;
  flex-flow: row wrap;
  margin-top: 100px;
}
.flex-item {
  width: 23%;
  height: 360px;
  margin: 10px;
  order: 1;
  border-radius: 3px;
  padding: 0 10px 40px 10px;
}
.colour-1 {
  background-color: #8c72cb;
}
.colour-2 {
  background-color: #54c7ec;
}
.colour-3 {
  background-color: #a3cedf;
}
.colour-4 {
  background-color: #b9cad2;
}
.colour-5 {
  background-color: #6bcebb;
}
.colour-6 {
  background-color: #a3ce71;
}

<div class="flex-container">
  <div class="flex-item colour-1"></div>
  <div class="flex-item colour-2"></div>
  <div class="flex-item colour-3"></div>
  <div class="flex-item colour-4"></div>
  <div class="flex-item colour-5"></div>
  <div class="flex-item colour-6"></div>
</div>

图片

谢谢.

推荐答案

您可以在 flex 容器上使用 justify-content 来将项目在其主轴上对齐.看看这个例子:https://jsfiddle.net/eL650y3e/

You can use justify-content on the flex container to align items over its main axis. Take a look at this example: https://jsfiddle.net/eL650y3e/

来源:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content
  • https://css-tricks.com/snippets/css/a-guide-to-flexbox/

相关文章