Display content in two columns (50% each), if content does not fit move column to next row and fill horizontal space

10,719

Solution 1

You can use flexbox and white-space: nowrap

Fiddle snippet

Stack snippet

.wrapper {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.left,
.right {
  flex: 1 0 50%;
  background: lightgreen;
  white-space: nowrap;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}
.right {
  background: lightblue;
}
<div class="wrapper">

  <div class="left">
   This is a longer text. This is a longer text. 
  </div>
  <div class="right">
  This is a shorter text. 
  </div>
  
</div>

<div class="wrapper">

  <div class="left">
   This is an even longer text. This is an even longer text.
  </div>
  <div class="right">
  This is a shorter text. 
  </div>
  
</div>

Solution 2

Using flex it is possible.

Have a look at this Fiddle I've made for you. Simply add more text to see the result.

Just use a flex-wrap and do some aligning and justifying of the content.

For this to work in a cross-browser environment, always use an Autoprefixer.

Share:
10,719

Related videos on Youtube

b2238488
Author by

b2238488

Updated on September 15, 2022

Comments

  • b2238488
    b2238488 over 1 year

    In my project, I want to display content in two columns (50% each), if content does not fit in, then move column to next row and fill horizontal space.

    Here are two images to show what I mean.

    For short text, display it in two columns:

    enter image description here

    When the text does not fit anymore, ie either of the columns are above 50% width, move the 2nd column's content in the next row filling all available horizontal space. Somewhat like this :

    enter image description here

    Can this be done only with CSS?

  • Asons
    Asons about 7 years
    With this text can grow beyond 50% width before it break line, which it is asked not to
  • Tanasos
    Tanasos about 7 years
    LGSon, have you even tried adding more text in either of the divs as I described in my answer before commenting?
  • Asons
    Asons about 7 years
    Yes, I filled left element with text and it only break when reaching right elements text width (+ padding) ... jsfiddle.net/a780srjh/1 ... which mean the elements are just before break not 50% wide each
  • b2238488
    b2238488 about 7 years
    Add min-width: 50% to the div and it's exactly what I needed.