Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox Text wrapping

Tags:

html

css

flexbox

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

like image 713
Konrad Avatar asked Oct 26 '25 06:10

Konrad


1 Answers

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> 
like image 133
Asons Avatar answered Oct 28 '25 20:10

Asons