This question already has answers here:
How to disable equal height columns in Flexbox?
                                
                                    (3个答案)
                                
                        
                                2年前关闭。
            
                    
使用flex-box收缩div的最佳方法是什么?
在下面的代码段中,除了底部以外,我都用包装纸(绿色边框)将内容(红色和蓝色框)收缩包装。

我怎样才能做到这一点?

这是一个小样的演示:https://plnkr.co/edit/u89JPIbZObTYIfRejlO1?p=preview



.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
}

.wrapper2 {
  border: solid green;
  padding: 5px;
}

<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>

最佳答案

您可以使用 :
align-items

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
  align-items:flex-start;/* update here */
}

.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
  align-items:flex-start;
}

.wrapper2 {
  border: solid green;
  padding: 5px;
  /*margin:0 auto auto*/
}

<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>

margin
.wrapper2 {
  border: solid green;
  padding: 5px;
  margin:0 auto auto/* update here */
}

.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
 /* align-items:flex-start;*/
}

.wrapper2 {
  border: solid green;
  padding: 5px;
  margin:0 auto auto
}

<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>

提醒/教程:

关于css - 如何使用flexbox收缩div? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45259979/

10-10 05:36