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

CSS Grid忽略max-height问题:Nonogram数织应用自适应布局异常求助

解决方案

核心溢出问题修复

溢出的核心原因是Grid布局中默认1fr等同于minmax(auto, 1fr),内容尺寸超过容器时会优先保留内容尺寸导致撑开,按以下步骤修改即可:

  1. 调整外层容器约束
    修改NonoGame.svelte中包裹NonoGrid的div类名,添加最大尺寸限制:
<div class="flex-shrink my-auto max-w-full max-h-[80vh] overflow-hidden">
  <div class="h-auto w-auto">
    <NonoGrid controller={controller} />
  </div>
</div>

注:80vh对应上下header、footer各占10vh后的剩余可用高度,可按需调整。

  1. 调整Grid容器样式
    修改NonoGrid.svelte中#grid-container的样式,替换1fr为minmax(0, 1fr)并添加尺寸限制:
#grid-container {
    display: grid;
    grid-template-rows: fit-content(100px) minmax(0, 1fr);
    grid-template-columns: fit-content(150px) minmax(0, 1fr);
    grid-template-areas: "x col"
                         "row cells";
    width: fit-content;
    height: fit-content;
    max-width: 100%;
    max-height: 100%;
}
  1. 改用Grid实现单元格布局,配合动态CSS变量
    不需要监听视口,只需要从gridStore中获取行列数注入CSS变量即可,修改如下:
    首先给#cell-container添加动态变量:
<div id="cell-container" 
  style:--row-count={$gridStore[0].length}
  style:--col-count={$gridStore.length}
  on:mousedown={dragSelector.onMouseDown}
  on:touchstart={dragSelector.onTouchStart}
>
  {#each $gridStore as column}
      {#each column.reverse() as gridCell}
      <NonoCell gridCell={gridCell} />
      {/each}
  {/each}
</div>

然后修改#cell-container样式:

#cell-container {
    grid-area: cells;
    display: grid;
    grid-auto-flow: column;
    grid-template-rows: repeat(var(--row-count), 1fr);
    grid-template-columns: repeat(var(--col-count), 1fr);
    width: 100%;
    height: 100%;
    min-width: 0;
    min-height: 0;
}
  1. 约束单元格尺寸
    给NonoCell组件添加以下样式,保证正方形且可自适应缩放:
.nono-cell {
    aspect-ratio: 1 / 1;
    width: 100%;
    height: 100%;
    min-width: 0;
    min-height: 0;
}

每5行/列添加间隔实现

不需要依赖Grid全局gap,用伪类或者渲染时加类名即可实现:

方案1:CSS伪类实现(无需修改JS逻辑)

/* 每5列后添加左侧间隔 */
#cell-container > :nth-child(5n + 1):not(:nth-child(1)) {
    padding-left: 2px;
}
/* 每5行后添加上侧间隔 */
#cell-container > :nth-child(n + calc(5 * var(--col-count) + 1)):nth-child(5n * var(--col-count) + 1) {
    padding-top: 2px;
}

方案2:渲染时加类名(兼容性更好)

循环渲染单元格时判断行列索引,每第5行的单元格加top-gap类,每第5列的单元格加left-gap类,再定义对应样式即可:

.left-gap {
    padding-left: 2px;
}
.top-gap {
    padding-top: 2px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:54:04