You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中CSS Grid适配屏幕且消除间距的实现方法

解决方法

问题原因

设置width:100vw后,网格总宽度(38×60=2280px)与容器宽度(100vw)不匹配,CSS Grid默认会将剩余空间分配给网格间隙或拉伸列宽,导致出现多余间距。

具体调整方案

  1. 自适应容器宽度,限制最大宽度
    用fit-content()让容器宽度匹配网格内容总宽度,同时设置max-width:100vw防止超出屏幕,添加overflow:auto保证内容超出时可滚动:

    .grid-container {
      display: grid;
      grid-template-columns: repeat(38, 60px); /* 固定38列 */
      grid-auto-rows: minmax(auto, auto); /* 行高适配内容 */
      width: fit-content();
      max-width: 100vw;
      height: 100vh;
      overflow: auto;
    }
    
  2. 修正无效的布局属性
    align-content是Flex布局属性,在Grid布局的.grid-item中无效,替换为Flex内部对齐属性(如需对齐内容):

    .grid-item {
      font-size: 25px;
      background-color: #00ff73;
      color: #000;
      display: flex;
      align-items: flex-start; /* 实现内容顶部对齐 */
    }
    
  3. 重置页面默认边距
    移除body默认边距,避免页面留白影响容器适配:

    body {
      margin: 0;
      padding: 0;
    }
    

效果验证

  • 行列数始终保持固定(38列,行数由数据长度决定)
  • 支持Ctrl+滚轮缩放,缩放过程中无额外间距
  • 屏幕尺寸变化时,容器自动适配,超出部分可滚动

内容的提问来源于stack exchange,提问作者Model Trainer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:31:01