使用 CSS Flexbox 对齐 Div

时间:2021-03-31 10:11:32

标签: html css flexbox

我一直在努力使用 flexbox 使以下布局正常工作: enter image description here

我尝试了下面的 HTML 和 CSS

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

.flex-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 0;
  margin: 0;
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 600px;
  height: 150px;
  margin-top: 10px;
  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}

这是不正确的结果: enter image description here

关于如何实现第一个布局的任何想法/建议?

2 个答案:

答案 0 :(得分:1)

要对 flexbox 中的元素重新排序,您需要使用 flex-order(顺序)。具体来说:

/* Element with number 1 */
.flex-container :nth-child(1) {
  order: 2;
}

/* Element with number 2 */
.flex-container :nth-child(2) {
  order: 3;
}

/* Element with number 3 */
.flex-container :nth-child(3) {
  order: 6;
}

/* Element with number 4 */
.flex-container :nth-child(4) {
  order: 5;
}

/* Element with number 5 */
.flex-container :nth-child(5) {
  order: 4;
}

/* Element with number 6 */
.flex-container :nth-child(6) {
  order: 1;
}

最后但并非最不重要的是,使用提供的代码,您仍然没有得到想要的结果,但框对齐为:

#6 #5
#1 #4
#2 #3

这是因为您应用了 flex-direction: column;。您需要删除该行。

.flex-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0;
  margin: 0;
}

.flex-item {
  box-sizing: border-box;
  background: tomato;
  padding: 5px;
  width: calc((100% - 20px) / 3);
  min-height: 150px;
  margin-top: 10px;
  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}

.flex-container :nth-child(1) {
  order: 2;
}

.flex-container :nth-child(2) {
  order: 3;
}

.flex-container :nth-child(3) {
  order: 6;
}

.flex-container :nth-child(4) {
  order: 5;
}

.flex-container :nth-child(5) {
  order: 4;
}

.flex-container :nth-child(6) {
  order: 1;
}
<div class="flex-container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
  <div class="flex-item">4</div>
  <div class="flex-item">5</div>
  <div class="flex-item">6</div>
</div>

答案 1 :(得分:1)

我不知道你想达到什么目的。您可以更改 HTML 中元素的顺序以获得所需的内容。如果您想保持 HTML 不变,您可以使用 css 属性 order

相关问题