【问题标题】:Dynamic sizing of tiles using CSS使用 CSS 动态调整图块大小
【发布时间】:2021-11-24 04:45:54
【问题描述】:

如何在行和列(每行 2 列)结构中排列视频图块,以便 1 个视频图块占据所有可用位置。但是,如果动态添加更多视频块,它们应该遵循网格结构,并且块应该变得更小,以不超过总面积。例如,在 3 个视频块的情况下,第一行的每一列中应该存在 2 个块,第二行的两列中应该有 1 个块。是否可以使用 CSS 来实现?

编辑:

为简化起见,让我们考虑 div 而不是视频图块:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  max-width: 37.5rem; 
}

.grid > * {
  background-color: #ddd;
  margin: 0 0 1rem; 
  padding: .5rem;
  text-align: center;
}
<div class="grid">
  <div>I’ll find something to put here</div>
   <div>I’ll find something to put here</div>
   <div>I’ll find something to put here</div>
</div>

这适用于偶数个 div,它们以每行 2 列排列。但是对于奇数的 div,剩下的 div 不会占据整个行宽。

【问题讨论】:

  • 请向我们展示您的基本 HTML 结构和任何相关的 CSS。你研究过不同的可能性吗? grid/flex/inline 和/或 JS?
  • @AHaworth 我已经编辑了我的帖子以添加一些代码。

标签: html css reactjs sass


【解决方案1】:

弹性解决方案:

#flex {
    background: gray;
    display: flex;
    flex-wrap: wrap;
    width: 300px;
    height: auto;
}
  
#flex > * {
    background: blue;
    flex-grow: 1;
    height: 100px;
    width: 40%;
    margin: 10px;
    text-align: center;
}
<div id="flex">
    <div class="video"></div>
    <div class="video"></div>
    <div class="video"></div>
</div>

【讨论】:

    【解决方案2】:

    您可以选择网格中的最后一个元素,同时指定它必须是奇数,如下所示:

    .grid div:last-child:nth-child(odd)
    

    并给它两倍的正常宽度。

    您必须仔细考虑在无法并排容纳两个“正常”div 且宽度不加倍的狭窄设备上究竟想要发生什么。

    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      max-width: 37.5rem;
    }
    
    .grid * {
      background-color: #ddd;
      margin: 0 0 1rem;
      padding: .5rem;
      text-align: center;
    }
    
    .grid div:last-child:nth-child(odd) {
      width: 200%;
    }
    <div class="grid">
      <div>I’ll find something to put here</div>
      <div>I’ll find something to put here</div>
      <div>I’ll find something to put here I am last</div>
    </div>

    【讨论】:

      【解决方案3】:
      .grid {
        display: flex;
        flex-wrap: wrap;
      }
      
      .grid > * {
        flex:1 1 45vw;
      
        background-color: #ddd;
        margin: 0 0 1rem; 
        padding: .5rem;
        text-align: center;
      }
      

      在这里

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-29
        • 2015-05-14
        • 2011-03-16
        • 1970-01-01
        • 2012-06-09
        • 1970-01-01
        • 1970-01-01
        • 2012-11-15
        相关资源
        最近更新 更多