0

Is there a responsive way (not using min-width) to minimise a width of a parent when children do not take the entire space that parent has, given that the width of the children is hard set?
Problem
Solution

.parent {
  display: flex;
  flex-wrap: wrap;
  border: 1px solid grey; 
}

.child {
  background: lightgrey;
  height: 50px;
  width: 40vw;
  margin: 10px;
}
<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
kaz
  • 11
  • 3

1 Answers1

1

Try to add width: fit-content; to your .parent

UPD: try this approach (using grid system)

.parent {
  display: grid;
  border: 1px solid grey;
  grid-template-columns: repeat(2, minmax(min-content, max-content));
  width: fit-content;
}

.child {
  background: lightgrey;
  height: 50px;
  width: 40vw;
  margin: 10px;
}
<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
</div>

<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>


<div class="parent">
  <div class="child" style="width: 30vw"></div>
  <div class="child" style="width: 33vw"></div>
  <div class="child" style="width: 27vw"></div>
  <div class="child" style="width: 35vw"></div>
</div>
Yaroslav Trach
  • 1,833
  • 2
  • 12
  • 18
  • 1
    or `max-content` will also do the trik. +1 – Nitheesh Jan 31 '22 at 12:42
  • Thanks for the answer. This solution does not work if there are more children. Max content does not work either, since it results in content overflow if there are more children. – kaz Jan 31 '22 at 12:45
  • @kaz I've made updates to be as flexible as it possible, take a look on updates – Yaroslav Trach Jan 31 '22 at 13:35
  • @YaroslavTrach Thanks for the answer. I will stick to it, since there is no simple solution to this problem as stated [here](https://stackoverflow.com/a/37413580/18080780). Would be nice to use auto-fit instead of hardcoded numbers but it does not work and renders each child on a different line. Just going to use media queries for this reason. Thanks again – kaz Jan 31 '22 at 14:26