Sean
Sean

Reputation: 2729

Flexbox: How can child one have a width of its content and child 2 fills rest of width

I have a situation where I want to flexbox children to be side by side. I want child one to have a width equal to the width of its content, and then child 2 to take up the remaining width of the parent.

I can't seem to make this work though

Here's what I have so far

.flex {
  display: flex;
}

.flex-child {
  flex-basis: 0;
  flex-grow: 1;
}

.flex-1 {
  flex-basis: content;
  background: red;
}

.flex-2 {
  background: green;
}
<div class="flex">
  <div class="flex-child flex-1">
    Child 1, Child 1, Child 1
   </div>
   <div class="flex-child flex-2">
    Child 2, Child 2, Child 2
   <div>
</div>

Upvotes: 0

Views: 904

Answers (2)

Temani Afif
Temani Afif

Reputation: 272608

Simply set the flex-grow to the second child

.flex {
  display: flex;
}

.flex-1 {
  background: red;
}

.flex-2 {
  flex-grow: 1;
  background: green;
}
<div class="flex">
  <div class="flex-child flex-1">
    Child 1, Child 1, Child 1
   </div>
   <div class="flex-child flex-2">
    Child 2, Child 2, Child 2
   <div>
</div>

Upvotes: 1

StefanBob
StefanBob

Reputation: 5128

Set the flex of each children. Flex-1 should not grow but be auto width (flex: 0 1 auto) and flex-2 should be able to grow, shrink, and be auto width (flex: 1 1 auto)

.flex {
  display: flex;
}

.flex-child {}

.flex-1 {
  flex: 0 1 auto;
  background: red;
}

.flex-2 {
  flex: 1 1 auto;
  background: green;
}
<div class="flex">
  <div class="flex-child flex-1">
    Child 1, Child 1, Child 1
  </div>
  <div class="flex-child flex-2">
    Child 2, Child 2, Child 2
    <div>
    </div>

Upvotes: 1

Related Questions