简体   繁体   English

Flexbox文字包装

[英]Flexbox Text wrapping

I have the following layout: 我有以下布局:

 .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> 

I would like my text to wrap inside the div .text1 and .text2 without disturbing the flexgrow . 我希望我的文本在div .text1.text2而不会影响flexgrow In other words, is there any way to force flexbox to stay at the same size no matter the text in it? 换句话说,有没有办法强制flexbox保持相同的大小,无论其中的文本?

I'm using Chrome. 我正在使用Chrome。 Codepen link: https://codepen.io/Konrad29/pen/Oxbmqx Codepen链接: https ://codepen.io/Konrad29/pen/Oxbmqx

By setting the flex-basis to 0 , you control the width (distribute the space) with flex-grow 通过将flex-basis设置为0 ,可以使用flex-grow控制宽度(分布空间)

Update these rules 更新这些规则

.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  */
}

This will make the text1 to take 1/3 of the available space and the text2 2/3. 这将使text1占用可用空间的1/3和text2 2/3。

Based on what content you will put in each text1/2 , you might also need to set min-width , which defaults to auto , to 0 to allow it the be smaller than its content 根据您将在每个text1/2放入的内容,您可能还需要将min-width (默认为auto )设置为0以允许它小于其内容

Updated codepen 更新了codepen

Stack snippet 堆栈代码段

 .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; } 
 <div class="main"> <div class="container"> <div class="text1">Lorem impsum pimpsum</div> <div class="text2">Tex2</div> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM