Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make all column widths equal to the length of the widest column

Tags:

I am trying to use the max-content option of grid-template-columns in such a way that all my columns have the width of the widest cell in the grid. The number of columns needs to stay dynamic.

Right now I have the CSS and HTML below. You can see that only the width of the first column depends on the widest cell in my grid (cell 1). So in the desired result all columns should have the width of cell 1. Could someone tell me how to obtain a grid with a dynamic number of columns and a column width that depends on the biggest cell in my grid?

.container {
  width: 400px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(max-content, 100px));
  grid-gap: 5px;
}

.item {
  background: yellow;
  border: 1px solid red;
}
<div class="container">
  <div class="item">1 I am a very very wide cell</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  <div class="item">10</div>
</div>
like image 383
Daan Klijn Avatar asked Jan 08 '20 10:01

Daan Klijn


1 Answers

Jquery solution

  1. get the maximum width of all items:
var maxWWidth =Math.max.apply(Math, $('.item').map(function(){ return $(this).width(); }).get());
  1. set it for all items
$('.item').width(maxWWidth);

check snippet:

$(function(){
var maxWWidth =Math.max.apply(Math, $('.item').map(function(){ return $(this).width(); }).get());
$('.item').width(maxWWidth);
});
.container {
  width: 400px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(max-content, 100px));
  grid-gap: 5px;
}

.item {
  background: yellow;
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="item">1 I am a very very wide cell</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  <div class="item">10</div>
</div>

Upvote if you like it

like image 105
Basil Avatar answered Sep 30 '22 20:09

Basil