flex布局中宽度自适应?高度为何不能自适应?

<!DOCTYPE html>
<html lang="en">

<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <style>
            .box {
                  margin: 50px auto;
                  width: 300px;
                  height: 300px;
                  display: flex;
                  flex-wrap: wrap;
            }

            .box div {
                  width: 100%;
            }
      </style>
</head>

<body>
      <div class="box">
            <div style="background-color: red;"></div>
            <div style="background-color: yellow;"></div>
            <div style="background-color: black;"></div>
      </div>
</body>

</html>

如上,为什么不能给box下面的div加上height的值?为什么设置width=100%后不换行则从左到右等分为三份?而设置height=100%换行后不能从上到下等分为三份?

采用flex布局后,box中的所有子元素div自动成为容器成员,你设置了flex-wrap属性为:wrap,元素的布局就会变成类似于这样了:

你想变成自上而下的样式,有个flex-direction属性,它有四个值,按你的需求去选择:

  • row(默认值):主轴为水平方向,起点在左端。
  • row-reverse:主轴为水平方向,起点在右端。
  • column:主轴为垂直方向,起点在上沿。
  • column-reverse:主轴为垂直方向,起点在下沿。

设置display: flex; 的时候,默认方向是横向的,即

flex-direction: row;

你可以设置

flex-direction: column; 来改变box 的方向让它的子元素竖向排列。

当你设置flex-wrap: wrap; 子元素和父元素同样高度的时候,也会换行显示。