rodorgas
rodorgas

Reputation: 1092

How to make flex div take only the needed space?

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>

Upvotes: 46

Views: 66649

Answers (5)

Angel Orozco
Angel Orozco

Reputation: 13

Try

.parent {
  display: inline-flex
}

/* child you want to grow as needed */
.child {
  flex: none
 }

Upvotes: 1

RoeldJ
RoeldJ

Reputation: 471

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

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

Upvotes: 2

Bhavesh
Bhavesh

Reputation: 1071

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

Upvotes: 9

Eduard
Eduard

Reputation: 9165

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

Upvotes: 14

Tormod Haugene
Tormod Haugene

Reputation: 3676

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.

Upvotes: 66

Related Questions