CodingLittle
CodingLittle

Reputation: 1857

How to have items in flexbox only take content width?

I have a container which has a display flex property and i set the flex-wrap to wrap.

Problem I am having is that I am getting to much space between items.

My code:

#container {
  display: flex;
  flex-wrap: wrap;
  width: 250px
}

.child {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: auto
}
<div id="container">
  <div class="child">Ss</div>
  <div class="child">Very very very long text text text</div>
  <div class="child">Small</div>
  <div class="child">Medium</div>
</div>

Image:

enter image description here

Can find code in action here:

Fiddle

Upvotes: 0

Views: 332

Answers (2)

Michael Benjamin
Michael Benjamin

Reputation: 372244

The flex-grow property distributes free space on the line, based on the value applied.

If you give all items flex-grow: 1, each item will consume equal space.

Since you have two items with flex-grow: 1, they split the space on the line 50-50.

Remove flex-grow. Use margins or padding.

Upvotes: 1

zAnthony
zAnthony

Reputation: 342

Remove the flex grow and add a gap to create a bit of a space between items.

#container {
  display: flex;
  flex-wrap: wrap;
  width: 250px;
  gap: 5px; /*emphasized text*/ 
}

.child {
  flex-shrink: 1;
  flex-basis: auto;
}

Upvotes: 1

Related Questions