使所有列的宽度等于最宽列的长度

问题描述 投票:3回答:1

我正在尝试使用max-contentgrid-template-columns选项,以使[[all我的列具有网格中最宽单元格的宽度。列数需要保持动态。

现在,我下面有CSS和HTML。您可以看到,只有第一列的宽度取决于网格中最宽的单元格(单元格1)。因此,在期望的结果中,所有列都应具有单元格1的宽度。有人可以告诉我如何获得具有动态列数和列宽的网格,该网格宽度取决于网格中的最大单元格?

.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>
html css css-grid
1个回答
2
投票
jQuery解决方案

    获取所有项目的最大宽度:

  • var maxWWidth =Math.max.apply(Math, $('.item').map(function(){ return $(this).width(); }).get());
      为所有项目设置它
  • $('.item').width(maxWWidth);

    检查代码段:

    $(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
  • © www.soinside.com 2019 - 2024. All rights reserved.