Leonel Aguirre
Leonel Aguirre

Reputation: 25

How to make parent div fit its width to child items width with flexbox?

I have a flex parent div with more elements inside, but parent width doesnt fits to child elements, How can I fix it?

Basicaly I want to display a dinamical bidimensional matrix with its dimensions setted by the user, so the amount of elements inside will vary and there will be some line breaks like I show in the code bellow, also the child elements have its width and height fixed.

.parent {
  display: flex;
  flex-wrap: wrap;
  background-color: silver;
  padding: 5px;
  border-radius: 10px;
}

.child {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background-color: gold;
  margin: 5px;
}

.line-break {
  width: 100%;
}
<div class='parent'>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='line-break'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>

Here is also a fiddle of the code: https://jsfiddle.net/NoisyApple/4g8n3vfL/3/

I expect the parent to automatically set its width to the elements inside it.

Upvotes: 1

Views: 1168

Answers (1)

Temani Afif
Temani Afif

Reputation: 272590

You can do this with a simple inline-block configuration:

.parent {
  display:inline-block;
  background-color: silver;
  padding: 5px;  
  border-radius: 10px;
  font-size:0; /*to remove whitespace:*/
  margin:5px;
}

.child {
  height: 40px;
  width:40px;
  display:inline-block;
  vertical-align:top;
  border-radius: 10px;
  margin:5px;
  background-color: gold;
  font-size:initial;
}

.line-break {
  display:block;
}
<div class='parent'>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='line-break'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>
<br>
<div class='parent'>
  <div class='child'></div>
  <div class='child'></div>
  <div class='line-break'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>

Upvotes: 1

Related Questions