Jens Törnell Jens Törnell - 5 months ago 32
CSS Question

Flex-wrap with equal width

I use

flex-wrap
in CSS. I want a layout that accept these conditions:


  • Use
    flex-wrap
    .

  • Use the same width of all the boxes/child elements.

  • Use the width of the largest child element. No fixed widths.

  • It's not required to fill the width of the container.

  • In the jsfiddle it would probably be 1 or 2 items on each row.



Is it possible with some clever css flex solution or do I need to use javascript?

https://jsfiddle.net/swysdq22/



.wrap {
width: 300px;
background: #fff;
}
.narrow {
display: flex;
flex-wrap: wrap;
}
.narrow > * {
background: #ccc;
border: 2px solid #fff;
padding: 10px;
color: #fff;
}

<div class="wrap">
<div class="narrow">
<div class="item1">
Longest sentence.
</div>
<div class="item2">
Short text.
</div>
<div class="item3">
Another text.
</div>
<div class="item1">
Longest sentence.
</div>
<div class="item2">
Short text.
</div>
<div class="item3">
Another text.
</div>
</div>
</div>




Answer

You can use map() and get() to return array of widths and then with Math.max you can find maximum value in that array and apply it as width on each item

var w = $('.narrow > div').map(function() {
  return $(this).width();
}).get();

var max = Math.max.apply(null, w);
$('.narrow > div').width(max);
.wrap {
  width: 300px;
  background: #fff;
}
.narrow {
  display: flex;
  flex-wrap: wrap;
}
.narrow >* {
  background: #ccc;
  border: 2px solid #fff;
  padding: 10px;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <div class="narrow">
    <div class="item1">
      Longest sentence.
    </div>
    <div class="item2">
      Short text.
    </div>
    <div class="item3">
      Another text.
    </div>
    <div class="item1">
      Longest sentence.
    </div>
    <div class="item2">
      Short text.
    </div>
    <div class="item3">
      Another text.
    </div>
  </div>
</div>

Comments