19

If you are using a Flexbox layout to layout some items in a row, the Flexbox container takes up the full width of whatever container it is in. How do you set the Flexbox container to only take up the width of it's child elements?

Take a look at the following example:

https://jsfiddle.net/5fr2ay9q/

In this example the size of the flexbox container extends beyond the child element's width. The typical way to fix something like this is display: inline but obviously that won't work because then it's not a flexbox container anymore.

Is it possible to do this?

.container {
  display: flex;
  flex-direction: row;
  outline: 1px solid red;
}

p {
  outline: 1px solid blue;
}
Can you make the flex container not 100% width but rather the width of the content itself?

<div class='container'>
  <img src='https://placehold.it/300x300'/>
  <p>
    This is some content hello world testing 123.
  </p>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165
Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • 6
    I disagree with marking question as a duplicate of [Difference between display:inline-flex and display:flex](https://stackoverflow.com/questions/27418104/difference-between-displayinline-flex-and-displayflex). It's a totally different question: the asker doesn't know that inline-flex is related to their "how do I?" question unless they already knew the answer to their question before asking it! – Daryn Jan 08 '18 at 12:02

1 Answers1

17

You can use display: inline-flex; (see Designating a Flexible Box):

.container {
  display: inline-flex;
  flex-direction: row;
  outline: 1px solid red;
}

p {
  outline: 1px solid blue;
}
Can you make the flex container not 100% width but rather the width of the content itself?

<div class='container'>
  <img src='https://placehold.it/300x300'/>
  <p>
    This is some content hello world testing 123.
  </p>
</div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209