如何用flexbox收缩包装div?

时间:2017-07-22 22:53:26

标签: css flexbox

使用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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

你可以使用:

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

&#13;
&#13;
.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*/
}
&#13;
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>
&#13;
&#13;
&#13;

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

&#13;
&#13;
.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
}
&#13;
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>
&#13;
&#13;
&#13;

提醒/背诵:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

答案 1 :(得分:1)

使用align-items: flex-start;

上的.container2媒体资源

&#13;
&#13;
.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;
}
&#13;
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>
&#13;
&#13;
&#13;