首页 > 解决方案 > 如何将 5 个盒子与 flex 对齐?

问题描述

我需要帮助根据线框预览对齐 5 个框: https ://projekty.freshynek.cz/images/hp-wireframe.png

在此处输入图像描述

1 号箱应占 50% 的宽度,其他仅占集装箱宽度的 25%,位于大箱的右侧。

.flex-container {
  width: 1170px;
  display: flex;
}

.text {
  margin: auto;
}

.flex-item {
  flex-direction: row;
}

.col-first {
  width: 50%;
  flex: 1;
}

.big {
  border-radius: 10px;
  width: 100%;
  height: 300px;
  background-color: pink;
}

.col-second {
  width: 50%;
  flex: 1;
}

.two,
.three,
.four,
.five {
  border-radius: 10px;
  width: 50%;
  height: 150px;
  background-color: turquoise;
}

.three {
  border-radius: 10px;
  width: 50%;
  background-color: turquoise;
}
<div class="flex-container">

  <div class="col-first">

    <div class="big">
      <div class="text">1. big</div>
    </div>

  </div>
  <!-- .col-first -->

  <div class="col-second">

    <div class="two">
      <p>2. small</p>
    </div>

    <div class="three">
      <p>3. small</p>
    </div>

    <div class="four">
      <p>4. small</p>
    </div>

    <div class="five">
      <p>5. small</p>
    </div>

  </div><!-- .col-first -->

</div><!-- .flex-container -->

我尝试使用 flexbox 对齐所有 5 个框,但找不到正确的方法。感谢您的任何帮助。

标签: cssflexbox

解决方案


您需要将以下 css 属性添加到.col-second类中。

  1. display: flex- 这是必要的,以便4 turquoise可以使用 flexbox 控制您的盒子。应用display:flex到后.col-second,它将作为这些盒子的父容器。
  2. flex-wrap: wrap- 这是必要的,以便当项目(总)超过父项的宽度时,它们会转移到下一行。没有这个,你的4 turquoise盒子将保持在一行而不是两行。flex-wrap仅当您拥有display:flex同一项目时才有效。

附上工作片段。

更多关于 flex-wrap 的信息

.flex-container {
  width: 1170px;
  display: flex;
}

.text {
  margin: auto;
}

.flex-item {
  flex-direction: row;
}

.col-first {
  width: 50%;
  flex: 1;
}

.big {
  border-radius: 10px;
  width: 100%;
  height: 300px;
  background-color: pink;
}

.col-second {
  width: 50%;
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}

.two,
.three,
.four,
.five {
  border-radius: 10px;
  width: 50%;
  height: 150px;
  background-color: turquoise;
}

.three {
  border-radius: 10px;
  width: 50%;
  background-color: turquoise;
}
<div class="flex-container">

  <div class="col-first">

    <div class="big">
      <div class="text">1. big</div>
    </div>

  </div>
  <!-- .col-first -->

  <div class="col-second">

    <div class="two">
      <p>2. small</p>
    </div>

    <div class="three">
      <p>3. small</p>
    </div>

    <div class="four">
      <p>4. small</p>
    </div>

    <div class="five">
      <p>5. small</p>
    </div>

  </div><!-- .col-first -->

</div><!-- .flex-container -->


推荐阅读