Display content in two columns (50% each), if content does not fit move column to next row and fill horizontal space
Solution 1
You can use flexbox
and white-space: nowrap
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.
Related videos on Youtube
b2238488
Updated on September 15, 2022Comments
-
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:
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 :
Can this be done only with CSS?
-
Asons about 7 yearsWith this text can grow beyond 50% width before it break line, which it is asked not to
-
Tanasos about 7 yearsLGSon, have you even tried adding more text in either of the divs as I described in my answer before commenting?
-
Asons about 7 yearsYes, 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 about 7 yearsAdd
min-width: 50%
to thediv
and it's exactly what I needed.