How to adapt a flex div's width to content

Issue

My idea is to give an adaptive div width. When I have just one item, the width should be the same as the item within the container div.

Any suggestion on how to do this?

#container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  max-width: 200px;
  padding: 10px;
  margin: 20px;
  background-color: blue;
}
#container .item {
  width: 80px;
  height: 50px;
  background-color: red;
  margin: 10px;
}
<div id="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div id="container">
  <div class="item"></div>
</div>

Solution

You can use display: inline-flex

#container {
  display: inline-flex;
  flex-direction: row;
  flex-wrap: wrap;
  max-width: 200px;
  padding: 10px;
  margin: 20px;
  background-color: blue;
}
#container .item {
  width: 80px;
  height: 50px;
  background-color: red;
  margin: 10px;
}
<div id="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div id="container">
  <div class="item"></div>
</div>

Answered By – Nenad Vracar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published