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

如何在@media(max-width:425px)下减小动态点阵网格的元素垂直间距?

解决动态点阵网格小屏幕垂直间距过大问题

问题原因

你之前设置.cell的height无效,核心原因是:

  • .cell作为Grid容器,高度默认由内部<i>标签的尺寸决定,而<i>使用aspect-ratio:1,高度会自适应自身宽度;
  • 整体布局的垂直密度由JS代码中cellHeight的计算逻辑控制,单纯修改CSS的height会被动态生成的布局覆盖。

两种可行解决方案

方案1:CSS快速调整圆圈尺寸

在@media screen and (max-width: 425px)媒体查询中,直接缩小<i>标签的尺寸并抵消空隙,压缩垂直方向的整体间距:

@media screen and (max-width: 425px) {
    .circles {
        display: grid !important;
        grid-template-columns: repeat(14, 1fr);
        min-height: 0;
        grid-gap: 0px 5px; /* 保留列间距,行间距设为0 */
        width: 100%;
    }

    .cell {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-gap: 0;
    }

    /* 新增:缩小圆圈并抵消缩放空隙 */
    .cell i {
        transform: scale(0.75); /* 缩放比例可按需调整 */
        margin: -1px; /* 抵消缩放后产生的额外空隙 */
    }
}

方案2:修改JS计算逻辑(根源优化布局)

在createCircles函数中,针对小屏幕调整cellHeight的计算逻辑,让每个.cell的高度更小,从根源压缩垂直间距:

function createCircles() {
    let headerHeight = document.querySelector('.header-wrapper').offsetHeight;
    let viewportHeight = window.innerHeight;
    let heroHeight = viewportHeight - headerHeight;
    let hero = document.querySelector('.custom-uw');
    hero.style.height = `${heroHeight}px`;

    const circles = document.querySelector('.circles');
    circles.innerHTML = '';
    const cellWidth = circles.offsetWidth / grid_columns;
    let cellHeight = (cellWidth - differential) / cellCircles;

    // 新增:小屏幕下缩小cellHeight
    if (window.innerWidth <= 425) {
        cellHeight *= 0.7; // 缩小30%,可根据需求调整比例
    }

    const rows = Math.floor(hero.offsetHeight / cellHeight);
    let html = '';
    let cell = '<div class="cell">';
    for (let i = 0; i < cellCircles; i++) {
        cell += '<i></i>';
    }
    cell += '</div>';
    for (let i = 0; i < grid_columns * rows; i++) {
        html += cell;
    }

    circles.innerHTML = html;
}

注意事项

  • 方案1适合快速微调,不会改变网格的行数结构;
  • 方案2会增加网格行数,从根源优化垂直密度,适合需要更紧凑布局的场景;
  • 两个方案可结合使用,达到更理想的显示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:45:06