简体   繁体   中英

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 . In other words, is there any way to force flexbox to stay at the same size no matter the text in it?

I'm using Chrome. Codepen link: https://codepen.io/Konrad29/pen/Oxbmqx

By setting the flex-basis to 0 , you control the width (distribute the space) with 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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