37

How do I make a flex div to take only the space needed? It is taking all available space.

I want to have lined up divs, wrapping when it needs. Problem is that the flex container takes more space than it actually needs.

Here’s an example http://cssdeck.com/labs/wvhe64ot

#outer {
    border: 5px solid green;
    width: 400px;
}
#container {
    display: flex;
    border: 5px dashed black;
    flex-wrap: wrap;
}
#container div {
    padding: 10px;
    border: 2px solid black;
}
Dashed border should be close to the small divs
<div id="outer">
  <div id="container">
    <div>Lipsum</div>
    <div>Lipsum</div>
    <div>Lorem ipsum dolor sit amet</div>
    <div>Lorem ipsum dolor sit amet</div>
   </div>
<div>
rodorgas
  • 962
  • 2
  • 12
  • 29
  • Have a look at [Make Div Width Equal To Child Contents](http://stackoverflow.com/questions/450903/make-div-width-equal-to-child-contents). – adamdc78 Feb 26 '15 at 01:23
  • Problem with display: inline is that I also need wrapping. Same applies to width: -webkit-max-content or intrinsic. – rodorgas Feb 26 '15 at 01:45

4 Answers4

60

You might be looking for the display: inline-flex property. It treats its children just like the display: flex property, except it itself does not automatically grow.

Tormod Haugene
  • 3,538
  • 2
  • 29
  • 47
  • 3
    Only works if there's no wrapping... I wanted wrap *and* parent div taking the smaller space possible. I'm thinking it can't be done with CSS because maybe the idea is: if there's wrapping/break, it's because the div wanted more than 100% of space, so even though width is reduced by breaking the elements continuity rearranging some childs in another row, conceptually it took more space than it could initially contain. So the width is considered to be 100%, making impossible to the parent div take only the needed space (same width of the largest "row" of childs). – rodorgas Apr 20 '16 at 02:57
  • 1
    It seems like you are right. I had a similar issue myself, and thought I would leave what worked for me. Unfortunately, that doesn't seem to work in your case! – Tormod Haugene Apr 20 '16 at 05:21
  • Perfect. Helped me a lot today. – RuntimeError Apr 16 '21 at 09:46
8

What helped me was setting this for column-directed elements:

align-items: flex-start
display: flex
flex-direction: column

or this for row-directed-elements:

display: flex    
justify-content: flex-start
Eduard
  • 8,437
  • 10
  • 42
  • 64
8

set flex-shrink: 0 on div that you what to take at least required space

Bhavesh
  • 819
  • 1
  • 17
  • 31
1

You can put flex-grow: 0 on the flex-items:

#container div {
    padding: 10px;
    border: 2px solid black;
    flex-grow: 0;
}
Roel4811
  • 431
  • 4
  • 4