Flexbox文字包装

时间:2017-09-24 09:53:58

标签: html css css3 flexbox

我有以下布局:



.main {
  height: 200px;
  width: 300px;
  border: 1px solid black;
  background-color: rgba(255, 46, 0, 0.5);
}

.container {
  height: 200px;
  width: 200px;
  margin: auto;
  border: 1px solid black;
  z-index: 2;
  background-color: white;
  display: flex;
  align-items: stretch;
  justify-content: center;
}

.text1 {
  border: 1px solid red;
  flex-wrap: nowrap;
  flex-grow: 1;
}

.text2 {
  border: 1px solid blue;
  flex-wrap: nowrap;
  flex-grow: 2;
}

<div class="main">
  <div class="container">
    <div class="text1">Lorem impsum pimpsum</div>
    <div class="text2">Tex2</div>
  </div>
</div>
&#13;
&#13;
&#13;

我希望我的文字包含在div .text1.text2内,而不会打扰flexgrow。换句话说,有没有办法强制flexbox保持相同的大小,无论其中的文本?

我正在使用Chrome。 Codepen链接:https://codepen.io/Konrad29/pen/Oxbmqx

1 个答案:

答案 0 :(得分:2)

通过将flex-basis设置为0,您可以使用flex-grow控制宽度(分配空间)

更新这些规则

.text1{
  border: 1px solid red;  
  flex-wrap:nowrap;
  flex:1 1 0;                      /*  updated  */
  min-width: 0;                    /*  might be needed as well  */
}
.text2{
  border: 1px solid blue;
  flex-wrap:nowrap;
  flex:2 2 0;                      /*  updated  */
  min-width: 0;                    /*  might be needed as well  */
}

这会使text1占用可用空间的1/3,text2 2/3。

根据您在每个text1/2中添加的内容,您可能还需要将min-width(默认为auto)设置为0,以允许它为小于其内容

Updated codepen

Stack snippet

&#13;
&#13;
.main{
  height: 200px;
  width: 300px;
  border: 1px solid black;
  background-color :rgba(255, 46, 0, 0.5);
}
.container{
  height: 200px;
  width: 200px;
  margin: auto;
  border: 1px solid black;
  z-index:2;
  background-color: white;  
  display: flex;
  align-items: stretch;
  justify-content:center;
}
.text1{
  border: 1px solid red;  
  flex-wrap:nowrap;
  flex:1 1 0;
}
.text2{
  border: 1px solid blue;
  flex-wrap:nowrap;
  flex:2 2 0;
}
&#13;
<div class="main">
  <div class="container">
    <div class="text1">Lorem impsum pimpsum</div>
    <div class="text2">Tex2</div>
  </div>
</div> 
&#13;
&#13;
&#13;