Robert Koritnik Robert Koritnik - 18 days ago 10
CSS Question

Flexbox wrapped content and resizing

I have a flexbox container with 4 elements.

.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}


I want to position items within like this:

┌────────────────────┬────────┐
│ FIRST item has │ SECOND │
│ longer multi-line │ │
│ text content │ │
├────────────────────┴────────┤
│ THIRD │
├─────────────────────────────┤
│ FOURTH │
└─────────────────────────────┘


So for 3rd an 4th it's rather easy by setting their
flex-basis: 100%
and that's fine.

I've got a problem with 1st and 2nd item.


  1. 1st item has quite a bit of content so it should wrap when it can't fit a single line

  2. 2nd item should have non-wrapped text and should take as much horizontal space as needed by its content.

  3. 1st space should take all remaining space.



The problem



I can't seem to make it work with
flex-basis
and
flex-grow
. If I set only the 1st to grow and not constrain it in width it will wrap the 2nd item into the next line. But if I do constrain it, then these wdth constrants can't really be flexible according to 2nd item's width which adjusts to its content.

Answer

I guess you can set:

  1. white-space: nowrap and flex: 0 1 auto for the second div,

  2. flex: 1 for the first div

See demo below:

body {
  margin: 0;
}
* {
  box-sizing: border-box;
}
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.container > div {
  border: 1px solid red;
}
.container div:nth-child(1) {
  flex:1;
}
.container div:nth-child(2) {
  white-space: nowrap;
  flex:0 1 auto;
}
.container div:nth-child(3),
.container div:nth-child(4) {
  flex-basis: 100%;
}
<div class="container">
  <div>FIRST itema has
    <br/>longer multiline longer multiline longer multiline longer multiline longer multiline longer multiline longer multiline 
    <br/>text content</div>
  <div>Some text content here and some more</div>
  <div>Some text</div>
  <div>Some text here</div>
</div>